Shailrshah

Modular Exponentiation

Jan 17th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.41 KB | None | 0 0
  1. import java.util.Scanner;
  2. class ModPow{
  3.     public static void main(String args[]){
  4.         Scanner sc = new Scanner(System.in);
  5.         int base = sc.nextInt();
  6.         int exp = sc.nextInt();
  7.         int n = sc.nextInt();
  8.  
  9.         //base^exp % n
  10.         base %= n;
  11.         int result = 1;
  12.         while(exp>0){
  13.             if((exp & 1)==1)
  14.                 result = (result*base) % n;
  15.             base = (base * base) % n;
  16.             exp >>= 1;
  17.         }
  18.         System.out.println(result);
  19.     }
  20. }
Add Comment
Please, Sign In to add comment