thieumao

Find cyclic number

Apr 15th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. import java.math.BigInteger;
  2. import java.util.Scanner;
  3.  
  4. public class Main {
  5.  
  6.     public static void main(String[] args) {
  7.         Scanner cin = new Scanner(System.in);
  8.         int n = cin.nextInt();
  9.         int x = cin.nextInt();
  10.         int b = x - 1;
  11.         if (n == 1) {
  12.             System.out.print(b);
  13.             return;
  14.         }
  15.         while (b > 1) {
  16.             if (checkCyclic(b, n + 1) == true) {
  17.                 System.out.print(b);
  18.                 return;
  19.             }
  20.             b--;
  21.         }
  22.         System.out.print(-1);
  23.     }
  24.    
  25.     private static boolean checkCyclic(int b, int p) {
  26.         if (checkBdivP(b, p) == true) {
  27.             return false;
  28.         }
  29.         if (checkPrime(p) == false) {
  30.             return false;
  31.         }
  32.         BigInteger bBig = new BigInteger(String.valueOf(b), 10);
  33.         BigInteger soMu = bBig;
  34.         for (int i = 2; i <= p-1; i++) {
  35.             soMu = soMu.multiply(bBig);
  36.         }
  37.         BigInteger pBig = new BigInteger(String.valueOf(p), 10);
  38.         BigInteger motBig = new BigInteger("1", 10);    
  39.         BigInteger soMuTru1 = soMu.subtract(motBig);
  40.         BigInteger koBig = new BigInteger("0", 10);
  41.         if (soMuTru1.mod(pBig).equals(koBig) == true) {
  42.             System.out.println(soMuTru1.divide(pBig));
  43.         }
  44.         return soMuTru1.mod(pBig).equals(koBig);
  45.     }
  46.    
  47.     private static boolean checkPrime(int number) {
  48.         if (number < 2) {
  49.             return false;
  50.         }
  51.         if (number == 2 || number == 3) {
  52.             return true;
  53.         }
  54.         for (int i = 2; i < number; i++) {
  55.             if (number % i == 0) {
  56.                 return false;
  57.             }
  58.         }
  59.         return true;
  60.     }
  61.    
  62.     private static boolean checkBdivP(int b, int p) {
  63.         return b % p == 0;
  64.     }
  65.    
  66. }
Advertisement
Add Comment
Please, Sign In to add comment