// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.math.*;

public class ModPow {
   private final static int N = 1000;
   public static int modpow1(int a, int b, int c) {
      int res = 1;
      for(int i = 0; i < b; i++) {
         res = ((a % c) *  res) % c;
      }
      return res;
   }
   public static int modpow2(int a, int b, int c) {
      if(b <= 1) {
         return (a % c);
      } else {
         return ((modpow2(a, b/2, c) % c) * (modpow2(a, b-b/2, c) % c) % c);
      }
   }
   public static void main(String[] args) {
      System.out.println(BigInteger.valueOf(1118).modPow(BigInteger.valueOf(25), BigInteger.valueOf(3293)));
      System.out.println(modpow1(1118, 25, 3293));
      System.out.println(modpow2(1118, 25, 3293));
      int res = 0;
      long t1 = System.currentTimeMillis();
      for(int i = 0; i < N; i++) res = modpow1(1234, 5678, 90);
      long t2 = System.currentTimeMillis();
      System.out.println(res + " " + (t2 - t1));
      long t3 = System.currentTimeMillis();
      for(int i = 0; i < N; i++) res = modpow2(1234, 5678, 90);
      long t4 = System.currentTimeMillis();
      System.out.println(res + " " + (t4 - t3));
   }
}
