/*
// Project Euler
// Problem #: 7
// By: TheEngineer
// Date: 09/12/10
*/
public class Euler7 {
public static void main(String args[]) {
int[] primes = new int[10002];
int tmp = 0;
for ( int i = 2; i < 10000000; i++ ) { // Search for primes up to the number 1,000,000
int j = 0; // primes[j] goes from places 0 to 10,001.
while ( j < 10002 ) {
if ( isPrime(i) && i > tmp ) {
primes[j] = i;
tmp = i;
j++;
}
break;
}
}
System.out.println(primes[10001]); // Print the 10,001st prime number
}
public static boolean isPrime( int x ) { // Checks to see if a number is prime
for ( int i = 2; i <= x / 2; i++ ) { // i starts at 2, while i < half of x (int i from main), incriment i by one each time we loop
if ( x % i == 0 ) { // if x is divisible by any number that is <= half of it, then x is NOT prime
return false;
}
}
return true; // If x isn't divisible by any number other than itself and one, then x IS prime
}
}
I tried commenting this time, hope that helps. The reason I decided to use a while loop, incrementing j by 1 each time, was because I thought this would save a lot of time. Rather than looping through every number between 2 and 1,000,000 over 10,000 times. I could be wrong but this makes sense to me.
Tell me why I am wrong please.

New Topic/Question
Reply



MultiQuote










|