I wrote a code that finds if a number is prime or not. for every prime number it prints the number + is prime for every number that isn't prime it prints the number=the lowest divider*the highest divider
only for the biggest int (2147483647) it prints the second line all though it is a prime number... why so?
the code:
import java.util.Scanner;
public class FindDivisors2meth {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int n = myScanner.nextInt();
boolean isPrime = true;
int p = 2;
while( p * p <= n & isPrime ) {
if( n % p == 0) {
isPrime = false;
}
else {
p = p + 1;
}
}
if( isPrime) {
System.out.println(n + " is prime");
}
else {
System.out.println(n + "=" + p + "*" + n/p);
}
}
}
When you try to input 2147483647, your program is treating it as an int, and due to the limitations of the data type, it overflows, causing unexpected behavior. You can try this 'Long' instead of 'int', it shall return 2147483647 is prime. :)