Advertisement
Guest User

Untitled

a guest
Oct 17th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.17 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.math.BigInteger;
  3.  
  4. class Main {
  5.     public static long mul(long a, long b, long mod){
  6.         if (a == 1) return b;
  7.         long tmp = mul(a/2, b, mod)%mod;
  8.         if (a%2 == 1) return (tmp + tmp + b)%mod;
  9.         return (tmp + tmp)%mod;
  10.        
  11.     }
  12.     public static long power(long a, long b, long mod){
  13.         if (b == 0) return 1;
  14.         if (b == 1) return a;
  15.         long tmp = power(a, b/2, mod)%mod;
  16.         tmp = (tmp*tmp)%mod;
  17.         if (b%2 == 1) return (tmp*a)%mod;
  18.         return tmp;
  19.     }
  20.    
  21.     public static void main (String[] args) throws java.lang.Exception {
  22.         Scanner sc = new Scanner(System.in);
  23.         int n = sc.nextInt();
  24.         for (int i = 0; i < n; ++i){
  25.             long k = sc.nextLong();
  26.             long a = sc.nextLong();
  27.             long b = sc.nextLong();
  28.             long base = sc.nextLong();
  29.             long r = mul(a, power(base, k-1, b), b);            // a*base^(k-1)  %b
  30.             BigInteger bR = new BigInteger(Long.toString(r));
  31.             BigInteger bBase = new BigInteger(Long.toString(base));
  32.             BigInteger bB = new BigInteger(Long.toString(b));
  33.             System.out.println(bR.multiply(bBase).divide(bB));  // r*base   %b
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement