Reputation: 3
Alright so I'm trying to set up a program that will find prime numbers. I've set up an array called primes with prime numbers up to 199. How can I create a while loop that pretty much says, while (x%primes[any number in primes] <= 0). I'm not sure what I should be putting to make it properly detect it. I know or statements are an option, I'm just wondering if there's a better way. Here's my code:
import static java.lang.System.out;
public class Problem3 {
public static void main(String[] args) {
/// What is the largest prime factor of the number 600851475143 ?
long x;
x = 600851475143L;
int[] primes = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
};
out.println(x);
//while (x % primes[*This is where I need clarification*] <= 0) {
int i = 0;
for (i = 0; i < primes.length; i++) {
//out.println("Term " + i + " is " + primes[i]);
if (x%primes[i] <=0) {
x = x/primes[i];
}
}
//}
out.println(x);
}
}
Upvotes: 0
Views: 37
Reputation: 201439
Your table of primes is too small (only 71
is a factor of 600851475143L
). Easiest fix, eliminate that table and iterate from three to the square root of your number incrementing by two. Like,
long x = 600851475143L;
for (int i = 3; i <= Math.sqrt(x); i += 2) {
if (x % i == 0) {
System.out.println(i);
x /= i;
}
}
System.out.println(x);
I get
71
839
1471
6857
And
71*839*1471*6857
600851475143
Upvotes: 1