• Post Reply Bookmark Topic Watch Topic
  • New Topic

Implement a method that computes all prime ≤ to the parameters passed to it?  RSS feed

 
Justin Robbins
Ranch Hand
Posts: 121
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Had this as an exam question and I was quite befuddled on how to solve.

Implement a method called prime that computes all prime numbers less than or equal or to the parameters passed to it (let us call it n) using the Sieve of Eratosthenes algorithm described below in pseudo-code:

1. Create an ArrayList called primeList and add 2 to it as the first prime number
2. For i between 3 and n
3. Set flag isPrime to true
4. For each integer j in primeList
5. If i is divisible by j set flag isPrime to false
6. End for each
7. If isPrime is true, add i to the primeList
8.End for
9. Return primeList
10. Fill in the body of the method below

public arraylist primesieve(int n){

}

Any steps would be greatly appreciated

Thank you
 
Paul Clapham
Sheriff
Posts: 22832
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a rather misleading set of instructions. In real life you would want an array representing integers from 1 to N, which you go through repeatedly marking some as non-prime, and a list representing known primes found so far. Those instructions don't mention anything like that.

Try it with pencil and paper first.
 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't say the instructions are misleading. Rather, they just describe an alternative approach to the usual boolean array. It's based on the fact that non-prime numbers are divisible by at least one smaller prime number. So, for each number you want to check, you'd iterate over the primes you have found so far, which are stored in the ArrayList, to see if any of them is a factor of the number being checked.
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is the procedure used in the Sieve of Eratosthenes, but taken backwards.
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What specifically are you having trouble with?
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if it was for an exam, what did you write? Are you aware of this class?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!