Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# problem in prime numbers using an array

alper cem polat
Greenhorn
Posts: 1
I'm designing a program to generate and calculate first 100 prime numbers according to the following:

The Intbag class holds the values of the collection. Through that class, i will calculate the first 100 prime numbers.

To generate the prime numbers, i want to divide each number by the prime numbers in the collection.

Here is the IntBag class :

Here is my main method :

But the program only generates the first 2 prime numbers(2 and 3). I tried many times but couldnt figure out why.?
can you help me?

Campbell Ritchie
Sheriff
Posts: 50258
79
Welcome to the Ranch

Why have you got that for loop with no continuation condition? Why have you nested it inside a while loop? Why do you have a constructor allowing you to set the size of your array and then test it against 100? You have a serious design flaw in the get(int) method; what happens if you have a 50-element array and look for no 60?

How are you calculating prime numbers? You ought to write it down on paper and get an algorithm working. Those three nested loops look very complicated to me, and suggest to me there is a better way to so that.

Campbell Ritchie
Sheriff
Posts: 50258
79
alper cem polat wrote: . . . The Intbag class . . . Through that class, i will calculate the first 100 prime numbers. . . .
No, you aren’t. You are using something else to try and calculate prime numbers.

You don’t think a Sieve of Eratosthenes would be better?

Matthew Brown
Bartender
Posts: 4568
9
Hi. Welcome to The Ranch!

Have a closer look at your prime variable. You initialise it to true, it gets set to false the first time you find a prime factor...and it never gets changed again.

Your combination of a while and for loop on lines 19 and 20 looks strange as well - all you're wanting to do is increment a until primes is full, so you only need one loop for that. It's not clear at the moment how the inner loop is ever going to end.

Matthew Brown
Bartender
Posts: 4568
9
Campbell's also right about the Sieve of Eratosthenes if you're looking for a good but simple way to generate primes (although in its simplest form that generates primes up to a particular value rather than a particular number of them).