Computer Science Canada

Need help for outputing prime number

Author:  Johnny19931993 [ Tue Feb 03, 2009 3:53 pm ]
Post subject:  Need help for outputing prime number

I'm trying to make a program that calculates all the prime numbers from 1 to 50
but i don't know why my program didn't output anything
can anyone help me?

Turing:

const QUANTITY := 50
var number : array 1 .. QUANTITY of int
var counter := 0

for x : 1 .. QUANTITY
    number (x) := x
    for y : 1 .. x
        if number (x) mod y = 0 then
            counter += 1
        end if
    end for
    if counter = 2 then
        put number (x)
    end if
end for

Author:  cavetroll [ Tue Feb 03, 2009 4:08 pm ]
Post subject:  Re: Need help for outputing prime number

Your problem is you need to reset the counter for every loop through. Try something like:


Turing:
const QUANTITY := 50
var number : array 1 .. QUANTITY of int
var counter := 0

for x : 1 .. QUANTITY
    counter := 0
    number (x) := x
    for y : 1 .. x
        if number (x) mod y = 0 then
            counter += 1
        end if
    end for
    if counter = 2 then
        put number (x)
    end if
end for

Author:  DanielG [ Tue Feb 03, 2009 5:33 pm ]
Post subject:  RE:Need help for outputing prime number

your mistake is going from 1 .. x, it should be 1.. x-1, also, make sure you don't check one, since it is NOT a prime but will be shown as one by the formula you have written

Author:  Johnny19931993 [ Tue Feb 03, 2009 10:03 pm ]
Post subject:  Re: RE:Need help for outputing prime number

DanielG @ Tue Feb 03, 2009 5:33 pm wrote:
your mistake is going from 1 .. x, it should be 1.. x-1, also, make sure you don't check one, since it is NOT a prime but will be shown as one by the formula you have written


even though my problem is already solved by the help of cavetroll, I still want to point out that the program will not output 1 whatsoever
because if i put
Turing:

for x : 1..1

the loop will only go once, therefore, it is impossible for the value of "counter" to be 2
so if "number" is equal to 1, the program will not output 1

Author:  andrew. [ Wed Feb 04, 2009 5:23 pm ]
Post subject:  RE:Need help for outputing prime number

Why don't you make it like if the number is 1, then put 1, if it's anything else, then go into your for loop.


: