Prime number program for java

13,777

Solution 1

just print i instead of j

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(i);
    }
}

Solution 2

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.

Share:
13,777
idude
Author by

idude

Updated on June 04, 2022

Comments

  • idude
    idude almost 2 years

    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