prime numbers
Author |
Message |
ashiphire
|
Posted: Thu Mar 05, 2009 9:32 am Post subject: prime numbers |
|
|
I've been trying to make a program that finds prime numbers but all I've been able to do is check if specific numbers are prime numbers not check if all are
can anyone help?
here's my code
Turing: | %if false is output then it is not a prime number
var number : int
put "please enter a number: " ..
get number
for decreasing i : number div 2 .. 2
if number mod i > 0 then
else
put"false"
end if
end for
put "finished"
|
Edit by Clayton: Code tags. |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Clayton
|
Posted: Thu Mar 05, 2009 9:34 am Post subject: RE:prime numbers |
|
|
You need to keep track of how many factors (or lack thereof) that you have found. Any more than 0 and you know that the number is not prime. |
|
|
|
|
|
Tony
|
Posted: Thu Mar 05, 2009 2:35 pm Post subject: RE:prime numbers |
|
|
more than 2
1 and number itself are valid factors for a prime
Edit: nevermind, I can see that Clayton was referring to the specific implementation above, that doesn't get to check either of those numbers. Also, the loop doesn't work well for confirming that 2 is prime. |
Tony's programming blog. DWITE - a programming contest. |
|
|
|
|
Vorpike
|
Posted: Tue Nov 20, 2012 3:00 pm Post subject: Re: prime numbers |
|
|
That just tells you whether a number is even...the code you're looking for is this
Turing: | % PROGRAM: Prime.t
% NAME: Vorpike
% DATE: November 16, 2012
% PURPOSE: Determines whether a number is a prime
var number : int
var count : int := 0
put "Enter number"
get number
for i : 2 .. number
count := count + 1
exit when number mod i = 0
end for
if count < number - 1 then
put number, " is not prime"
elsif count = number - 1 then
put number, " is prime"
end if
|
Basically, you check if any number between 2 and the number is divisible, and exit when a match is found, the count is to prevent submitting both messages "is prime" and "not prime".
Sorry for the late reply, just got on this forum...hate the registration, took me 10 tries to get past the confirmation code...how does one get the turing embed
EDIT (by AJ): added code tags |
|
|
|
|
|
Panphobia
|
Posted: Tue Nov 20, 2012 3:05 pm Post subject: RE:prime numbers |
|
|
Basically make a for loop from 1, half the number you are checking, then check if the num mod counter not= 0 c+=1 and if c is equal to the num/2 -1 then it is a prime |
|
|
|
|
|
A.J
|
Posted: Thu Nov 22, 2012 2:01 pm Post subject: RE:prime numbers |
|
|
@ashiphire- Based on your question, I am assuming that you are looking for a method to check if some set of numbers are prime without individually checking each number. One well known way of finding all primes less than or equal to some specific number is the Sieve of Eratosthenes (wiki does a pretty good job at explaining what this is: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). |
|
|
|
|
|
|
|