Prime number program for java

idude picture idude · Mar 25, 2013 · Viewed 13.8k times · Source

I'm new to programming and need help on a java program. I want my program to return all the prime numbers between 1 and 10.

    for(int i=1; i<=10; i++){
        int factors = 0;
        int j=1;

        while(j<=i){
            if(i % j == 0){
                factors++;
            }
            j++;
        }
        if(factors==2){
            System.out.println(j);
        }
    }

Instead of receiving 2,3,5 and 7 I receive 3,4,6,and 8

Answer

Veger picture Veger · Mar 25, 2013

You print j instead of i, change your println() line to:

System.out.println(i);

Your results are 'one too large' as j = i + 1 after the while-loop.