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]

2 thoughts on “Algorithm to find first n prime number

  1. made adi 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);
    }
    }

  2. lamida berkata:

    made adi :
    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.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s