Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime number program for java [closed]

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

like image 846
idude Avatar asked Jul 18 '26 17:07

idude


1 Answers

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.

like image 57
Veger Avatar answered Jul 20 '26 07:07

Veger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!