Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.BigInteger;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner cin = new Scanner(System.in);
- int n = cin.nextInt();
- int x = cin.nextInt();
- int b = x - 1;
- if (n == 1) {
- System.out.print(b);
- return;
- }
- while (b > 1) {
- if (checkCyclic(b, n + 1) == true) {
- System.out.print(b);
- return;
- }
- b--;
- }
- System.out.print(-1);
- }
- private static boolean checkCyclic(int b, int p) {
- if (checkBdivP(b, p) == true) {
- return false;
- }
- if (checkPrime(p) == false) {
- return false;
- }
- BigInteger bBig = new BigInteger(String.valueOf(b), 10);
- BigInteger soMu = bBig;
- for (int i = 2; i <= p-1; i++) {
- soMu = soMu.multiply(bBig);
- }
- BigInteger pBig = new BigInteger(String.valueOf(p), 10);
- BigInteger motBig = new BigInteger("1", 10);
- BigInteger soMuTru1 = soMu.subtract(motBig);
- BigInteger koBig = new BigInteger("0", 10);
- if (soMuTru1.mod(pBig).equals(koBig) == true) {
- System.out.println(soMuTru1.divide(pBig));
- }
- return soMuTru1.mod(pBig).equals(koBig);
- }
- private static boolean checkPrime(int number) {
- if (number < 2) {
- return false;
- }
- if (number == 2 || number == 3) {
- return true;
- }
- for (int i = 2; i < number; i++) {
- if (number % i == 0) {
- return false;
- }
- }
- return true;
- }
- private static boolean checkBdivP(int b, int p) {
- return b % p == 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment