0

I need to write a program to find the first 10 prime numbers, i.e. integers that are only evenly divisible by themselves and 1. The hint I got was to make a big array of booleans named "isprime" and mark off all the non-prime numbers as false, i.e. isprime[4] = false. Here's what I have but it's just printing all of the numbers anyway.

public class PrimeFinder 
{
    public static void main(String[] args) 
    {
        boolean[] isprime = new boolean[100];
        
        for(int i = 2; i < isprime.length; i++)
        {
            if(i-1 % i == 0)
            {
                isprime[i] = false;
            }
            isprime[i] = true;
        }
        
        for(int j = 0; j < isprime.length; j++)
        {
            if(isprime[j] == true){
            System.out.print(j);
            System.out.print(", ");
            }
        }
    }
}
3
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by JamesCherrill
1
if(i-1 % i == 0)
            {
                isprime[i] = false;
            }
            isprime[i] = true;

even if it ran through the if statement the value of isprime will still be changed to true, try using an else statement

Edited by zeroliken: n/a

0

The code that zeroliken quoted is your problem. Each time you loop with a new value of i you overwrite all the values from the previous pass of the loop.
The correct way to do the sieve algorithm is to start with the isPrime array set to all true, then in your loop change that to false for any number that you find to be not a prime. Never set any back to true again! When all the looping is finished any element of isPrime that is still true represents a prime number.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.