# Algorithm to find first n prime number

For second time I found same problem that I can’t solve well when attending job interview. Oh how is so hard become real programmer. The problem is: “Please make algorithm to list all of prime number from 1 to 100”. Ok, I know stupid definition of prime number. A prime can only divide by 1 and itself. For example 3 is prime because it is only divisible by 1 and 3 itself. 4 is not prime. Beside 1 and 4, 4 also divisible by 2. Ok stop talking and show me the code. After trial and error (and try to sneak by googling) I finally can make working method to list all of prime from n number. I write it in Java. Hopefully by writing this I don’t make third mistake. So at another interview I can confidently answer that easy question. Enjoyy.

public void countPrime(int n) {
boolean flag = true;
for (int i = 2; i <= n; i++) {// looping through all number for (int j = 2; j <= i - 1; j++) { // we check each number whether can be divided by other than 1 and itself if (i % j == 0) { flag = false; // not prime } } if (flag) { // we print the prime System.out.println(i); } else { flag = true; } } } [/code]

Iklan

## 2 respons untuk ‘Algorithm to find first n prime number’

Mungkin cara pemrograman yang di bawah ini bisa menghemat CPU cycle, yaitu dengan menggunakan break.

public void countPrime(int n) {
boolean flag = true;
for (int i = 2; i <= n; i++) {// looping through all number
flag = true; //reset the condition for a new number to be analysed
for (int j = 2; j <= i – 1; j++) {
// we check each number whether can be divided by other than 1 and itself
if (i % j == 0) {
flag = false; // not prime
break;
}
}
if (flag) { // we print the prime
System.out.println(i);
}
}

2. lamida berkata:

Mungkin cara pemrograman yang di bawah ini bisa menghemat CPU cycle, yaitu dengan menggunakan break.
public void countPrime(int n) {
boolean flag = true;
for (int i = 2; i <= n; i++) {// looping through all number
flag = true; //reset the condition for a new number to be analysed
for (int j = 2; j <= i – 1; j++) {
// we check each number whether can be divided by other than 1 and itself
if (i % j == 0) {
flag = false; // not prime
break;
}
}
if (flag) { // we print the prime
System.out.println(i);
}
}

Sepertinya iya mas. Thanx.