The original assignment question is simply to input a number from the user and find the nearest prime number greater than the number input by the user.
So far I've come up with the following:
package pack;
import java.io.*;
import java.util.*;
public class Lab1 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
//Declare variables
String input ;
int UserNumber = 0;
int prime = 0;
boolean yes = false;
int n1 = 0;
int n2 = 0;
//Prompt user.
System.out.println("Please enter an integer");
// Get input from user, change to integer
input = reader.readLine();
UserNumber = Integer.parseInt(input);
prime = UserNumber;
Random rand = new Random();
int randomNum = rand.nextInt((prime -1) +1) + 1;
while (yes != true) {
if ((randomNum ^(prime -1)) == (1 % prime)){
yes = true ;
}
else{
yes = false;
prime++;
}
}
System.out.println("The first prime number greater than " + UserNumber +" is " + prime);
}
}
I decided to go ahead and use Fermat's little theorem as the basis for my algorithm, but for some reason I can't get the code to output any results that seem even remotely correct.
If I put in 45 (the next available prime should be 47) but my results will constantly vary from infinite loops to arbitrary numbers.
What am I doing wrong?
I've narrowed it down to two possibilities. It's either the way I'm doing the math in the theorem or the randomization function.
Extra info:
Fermat's little theorem states that for any integer a between 1 and p, where p is a prime number, then a^(p-1) == 1 mod p
Please help. I feel stupid

New Topic/Question
Reply




MultiQuote




|