Finding Prime number..
Author |
Message |
scott326
|
Posted: Tue Mar 06, 2007 7:39 pm Post subject: Finding Prime number.. |
|
|
hey guys.. I have to make a program which lists all the prime numbers between 1 and 300 using loop...
I really don't know how to do it...
can anybody help me?
please... thank you |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Clayton
|
Posted: Tue Mar 06, 2007 7:46 pm Post subject: Re: Finding Prime number.. |
|
|
well, you know a prime number is a number that is divisible by 1 and itself. So, what you have to do for any given number is find all of it's factors right? If there is no factors other than 1 and itself, then we know that the number is prime |
|
|
|
|
|
Cervantes
|
Posted: Tue Mar 13, 2007 11:04 am Post subject: RE:Finding Prime number.. |
|
|
You might try using a common method known as the Sieve of Erastothenes. Basically, you write down all the numbers from 2 up to whatever n, then cross out all multiples of 2, then go to the next number: 3. Cross out all multiples of 3. Go to the next number. Well, we've already crossed out 4, because it's a multiple of 2, so the next number is 5. Cross out all multiples of 5. Continue like this, and you get the primes you want.
You can stop this process when you reach the square root of n. |
|
|
|
|
|
PaulButler
|
Posted: Tue Mar 13, 2007 6:46 pm Post subject: RE:Finding Prime number.. |
|
|
I usually go with a lazy (easy) method:
Check if the number is divisible by 2
if so, the number is composite
If not:
x = 3
while x is less than sqrt(n), see if n % x == 0
if n % x is 0, the number is composite.
if no value of x is a factor of n, the number is prime.
Cervantes' method is better suited to your problem, though. My method is best for situations where you don't have much memory.. I mostly use it on a graphing calculator to factor numbers. |
|
|
|
|
|
bugzpodder
|
Posted: Tue Mar 13, 2007 6:48 pm Post subject: RE:Finding Prime number.. |
|
|
for n=3000? brute force it, you use less memory with essentially no penality in time. algorithm is easier to write too |
|
|
|
|
|
|
|