import java.math.BigInteger;
import java.util.Scanner;
import java.io.File;

public class Q6{
    public static void main (String[] args) {
        BigInteger n = new BigInteger("3156478917144031");
        BigInteger div = new BigInteger("3");
        BigInteger one = new BigInteger("1");
        BigInteger p = new BigInteger("1");
        BigInteger q = new BigInteger("1");

        //Factor n!
        while (true) {
            //Found the divisor!
            if (n.mod(div).equals(new BigInteger("0"))){
                p = div;
                q = n.divide(div);
                break;
            }
            div = div.add(new BigInteger("2"));
        }

        // Print out factorization and phi.
        BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));
        System.out.println("p = "+p+" and q = "+q+" phi(n) = "+phi);

        // find d.
        BigInteger e = new BigInteger("926002123823977");
        BigInteger d = e.modInverse(phi);
        System.out.println("Decryption exponent: "+d);

        Scanner fin = null;
        // open file with ciphertext.
        try {
            fin = new Scanner(new File("message.txt"));
        } catch(Exception ex) {
            System.out.println(ex.getClass());
        }
        while (fin.hasNext()) {
            // Read in this block and create the bigInt.
            BigInteger cipher = new BigInteger(fin.next());
            BigInteger plain = cipher.modPow(d,n);
            System.out.println(plain);;
        }
        fin.close();
    }
}
