So I know my students are having a tough time with this one. All I asked them to do was to :
-create a method that checks if a number is prime
-modify the program to print the first n prime numbers
Of course it is a bit tricky but easy to do so here is my code and i will explain it in a bit:
public class PrimeNumber {
public static void main(String[] args) {
int count = 0, n = 15;
boolean flag = true;
for (int j = 2; flag == true; j++) {
if ((isPrime(j)) && (count < n)) {
System.out.print(j + " ");
count++;
}
if (count == n) {
flag = false;
}
// System.out.println(flag);
}
}
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
So basically all that happens here is that a prime number only has two factors. The method isPrime takes a parameter n which will be checked whether its prime or not. So I decided to start at i=2 because 2 is the first prime number.
if (n % i == 0) {
return false;
}
This if statement will check if there are any other factors that can divide the number n, if the factors exist then n is not prime. Study it and run it and see if you can make something out of it. Happy coding
Monday, 16 February 2015
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment