0
could anyone please explain me the code below it seems to be more complicated for me.
public class projecteuler7 { public static void main(String[] args) { int number = 3; int answer = 0; int count = 1; while (count < 10001) { if (getPrime(number)) { count++; answer = number; } number++; } System.out.println(answer); } public static boolean getPrime(int i) { long check = i; for (int k = 2; k <= Math.sqrt(check); k++) { if (check % k == 0) { return false; } } return true; } }
2 Respostas
+ 3
Here we have two Methods.
The main method will give you the first 1000 prime numbers greater than 3 this is achieved with the while loop.
Although 1 and 2 are also prime numbers.
The if (getPrime(number)) calls the getPrime method with the current number variable.
This is the int i variable in public static Boolean getPrime(int i).
This is then checked to see if it is a prime number and returns either true or false.
if the method returns true the variables count is increased and answer is modified to equal number. The number variable is then increased regardless of wether true or false was returned the answer is printed to screen and the while loop continues as long as count is less than 1001.
+ 2
//Class name: projecteuler7
public class projecteuler7 {
//main execution
public static void main(String[] args) {
int number = 3;
int answer = 0;
int count = 1;
//While will run 1000 times printing the value of "answer"
while (count < 10001) {
//See if the number return True, if true : couunt ++ and answer get the value of "number"
if (getPrime(number)) {
count++;
answer = number;
}
//every loop plus 1 on "number"
number++;
}
//print "answer"
System.out.println(answer);
}
public static boolean getPrime(int i) {
long check = i;
//run a loop using the square root of the "i" as limit
for (int k = 2; k <= Math.sqrt(check); k++) {
//See if the mod division is equal 0
if (check % k == 0) {
return false;
}
}
return true;
}
}
Print: 104743