0
How to find prime numbers in a series of numbers?
How to find prime numbers in a series of numbers. I understand it, but I don't know use the loop correct. Can you help me a little, please?
2 Answers
+ 4
(C++)
for(int d=1;d<=100;d++)
if(n%d==0)
cont++;
if(count==2)
cout<<"Prime.";
else
cout<<"Not prime.";
This is probably the simplest way of finding whether a number is prime or not.
The first line is the FOR loop, it gives new divisors to the last number of the range.
The second line is the IF statement, it checks whether the divisor from the FOR loop returns no remainder. If that's true than 1 gets added to the count variable (third line).
If the count variable has a total value of 2 (1 and the number itself) than the number is prime, otherwise the number isn't prime (line 4+).
Hope this helps!
+ 3
There are many ways. A simple one is the *Sieve of Eratosthenes* algorithm.
https://en.m.wikipedia.org/wiki/Sieve_of_Eratosthenes
1) take a range (e.g. 2 .. n),
2) mark them all as candidate
3) for all numbers in range, take next that is a candidate
3.1) number is prime? >> Print the number (or remember it)
3.2) mark all multiples of this number as not being a candidate anymore
Done.