Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

issue 2024 Fermat_Little_Theorem java #2264

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Fermat_Little_Theorem/Fermat_Little_Theorem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
x^(n-1) cong== 1modn
where x and n are coprime (gcd is 1)
multiplying by x inverse on both sides
x inverse = x^(n-2) mod n which is found using fast modular exponentiation
*/
public class Fermat_Little_Theorem {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int x;
int n;
System.out.println("Enter space separated coprime numbers x and n");
String input[] = br.readLine().split(" ");
x = Integer.parseInt(input[0]);
n = Integer.parseInt(input[1]);
findModInverse(x,n);
}
public static void findModInverse(int x, int n){

if(recursiveGCD(x,n)!=1){
System.out.println("inverse does not exist! returning...");
return;
}
else{
System.out.println("Modular Multiplicative inverse is..."+ fastModuloExponentiation(x,n-2,n));
}


}
public static int recursiveGCD(int a, int b){
return a==0 ? b:recursiveGCD(b%a,a);
}

public static long fastModuloExponentiation(int number, int power, int modulus){
if(power==0)
return 1;
if(power==1)
return number;
long sub_number = fastModuloExponentiation(number,power/2,modulus)%modulus;
if(power%2==0)
return (sub_number*sub_number)%modulus;
else
return ((sub_number*sub_number)%modulus * number%modulus)%modulus;
}
}

/*
input :
3 11
output :
Modular Multiplicative inverse is...4
*/