0
finding prime number in C
what is the algorithm to find prime numbers before an integer?
9 odpowiedzi
+ 9
Neko yep something like this (pseudo code):
a=array()
x=input()
for i from 2 to x:
if is_prime(i):
a.add(i)
Ok indeed it's just a question not an assignement 👍👍
+ 6
Have you tried it yourself ? Could you please post your attempt ? Anyway, otherwise you could've use the searchbar to get some inspiration...
https://www.sololearn.com/discuss/346738/?ref=app
https://www.sololearn.com/discuss/1218689/?ref=app
https://www.sololearn.com/discuss/810570/?ref=app
https://www.sololearn.com/discuss/736058/?ref=app
+ 6
Your idea is good, but to make it simpler I would've just make a is_prime() function and then use your for() loop to select primes.
By the way, is this an assignement ?
+ 5
Matin Zamani the idea of
Neko idea is good, but to make it simpler I would've just make a is_prime() function and then use your for() loop to select primes.
+ 3
For finding all primes smaller than an integer, the Sieve of Eratosthenes is a highly efficient algorithm, and not too difficult to implement.
You'll find the description, including a pseudocode, here: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
+ 2
I checked the wikipedia for that but I didn't get one point on the pseudocode which that suggest and that is making an array of Boolean values,actually I didn't get the point of the first line ! what does this mean?(the pseudocode is here:
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
A[j] := false.
)
+ 1
By function, do you mean instead using the while loop, calling a function?
And nah i was just checking on forums waiting for an answer on my question hopefully. Its not my assignment.
+ 1
Matin Zamani A Boolean data type just takes two values: True or False. There are ways to use Boolean variables in C, but for simplicity, you could just make your A an array of integers, and use only 1 or 0 instead of True or False. Does the rest make sense?
0
i guess you mean first giving an input and then get system to print them. on cpp after i take the integer i use a "for" loop with a condition like
for (int x=2;x<=_inputvar;x++)
then in that loop i add another loop with a while or perhaps another for to test the modulus=0 on its previous numbers starting from 2. i think if modulus test only has one positive answer, then its a prime number.
i leave the execution to you :p
hope it helps!