Write a class PrimeGenerator
that starts "at the beginning" of the prime numbers. Every time the method nextPrime()
is called, the next successive prime value is returned.
How? By adding one to the last prime it found, and running through all the numbers from 2 to the number we're checking (or the square root of that number if we want to be a little more efficient), and seeing if any of those numbers divide into our candidate. If they don't, the candidate is our new prime number, and we need to remember it and return it.
For example, if we know that 5 is a prime, how do we go about figuring out what the next prime is? Add one, start trying to divide by every previous number; it's not very efficient but that's all we have at this point. If one of the numbers we're testing is evenly divisible, then we know this candidate is not a prime. If we do make it all the way through those values without it dividing evenly, we know it must be a prime.
Once you've written and tested PrimeGenerator
, write a program PrimeRunner
that prompts the user for an integer and then prints out all prime numbers up to that integer.
Sample interaction:
Enter an integer and I'll show you all the primes up that value: 20
2
3
5
7
11
13
17
19