I’m in an introductory Java class and recently finished an assignment, however I have a query. I didn’t have chance to ask my professor yet, and it’s somewhat irrelevant to what we’re doing anyhow.
We basically have a software that checks to see if a user-inputted number is prime or not. If it isn’t a prime number, it finds the nearest prime number that is less than the input. As an example:
Enter an integer: 4
4 is not a prime number. The closest prime number is 3.
If the input is not prime, the programme operates as planned by employing a loop. Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
System.out.print("Please enter a positive, non-zero integer: ");
number = input.nextInt();
input.close();
if (isValid(number) == true) {
if(isPrime(number) == true) {
System.out.printf("%d is a prime number.", number);
} else {
switch(number) {
case 1:
System.out.print("1 is not a prime number. \n");
System.out.print("We cannot find the nearest prime.");
break;
default:
System.out.printf("%d is not a prime number.", number);
System.out.printf("\nThe nearest prime number is %d.", getNearestPrime(number));
}
}
} else {
System.out.print("Invalid input. Please run again.");
System.exit(1);
}
}
public static boolean isValid(int number) {
if (number > 0) {
return true;
} else {
return false;
}
}
public static boolean isPrime(int number) {
int i;
if(number == 1) {
return false;
} else {
for(i = 2; i < number; i++) {
if(number%i == 0) {
return false;
}
}
return true;
}
}
public static int getNearestPrime(int number) {
do {
number--;
} while (isPrime(number) == false);
return number;
}
It’s worth noting that we were obliged to design the three major approaches described below.
My concern is, is there a method to improve performance in this circumstance while calculating bigger ints?
If I enter 2,147,483,647, the software recognises it as a prime in around 10 seconds. When I input 2,147,483,646, it takes about the same amount of time to get the nearest prime.
I understand why this occurs, however after reading this information, it appears that any high level Java programmes I’ve encountered can compute far more sophisticated things far faster than my basic software.
I’m truly interested in how experienced programmers handle situations like these. Thank you very much!