2016年5月12日 星期四

UVA 374: Big Mod

Q374: Big Mod

計算 R = BP mod M
對相當大的B、P、M請寫一個有效率的演算法來。
Input
每筆測試資料有3行,各有1個整數分別代表B、P、M。
其中 0 <= B <= 2147483647      0 <= P <= 2147483674      1 <= M <= 46340
Output
輸出計算的結果,每筆測試資料一行。
Sample input
3
18132
17

17
1765
3

2374859
3029382
36123
Sample Output
13
2
13195

http://luckycat.kshs.kh.edu.tw/homework/q374.htm

import java.util.Scanner;

public class UVA_374 {

 public static void main(String[] args) {
  Scanner sc=new Scanner(System.in);
  while(true){
   System.out.println();
   int B=sc.nextInt(),P=sc.nextInt(),M=sc.nextInt();
   long R=1;
   for(int i=1;i<=P;i++){
    R*=B;
    R%=M;
   }
   System.out.println(R);
  }

 }

}

沒有留言:

張貼留言