task:
Function prototype: Should return a `bool` (because it answers a yes/no question) and should take in a single int (to ask whether it's prime).
- An int greater than 2 is prime if it is not divisible by any number between 2 and itself, not including itself.
- Use this function to print out the primes less than 50. Check it against my list:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
bool prime(int&x)
{
if (x%2==1)
returntrue;
elsereturnfalse;
}
int main()
{
for (int i = 0; i < 50; i++)
if ( prime(i) )
cout << i << " ";
return 0;
}
Taking your definition.
for example, if I want to test 15 is a prime or not, I will keep on dividing 15 from 2 - 8 (15/2) and if it can be divided by any of the numbers in between, its not a prime. This is what I have written and @catfish has coded for you.
the result looks correct, isn't it ? (a couple of things are not correct, but I guess you can correct them)
To quickly search for a prime
you only need to divide by odd numbers up to the square root of the number your checking.
You want to search for primes in order so you will want 2 loops I think.
(pseudo code)
// may not be 100% correct but it's to give you the idea.
// you start with 3 and add 2 which means you only check the odd numbers.
// since you are not checking even numbers, you don't need to divide by 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
while (num<=50)
{
int num=3;
find the sqrt(num)
while (x<=sqrt(num))
{
if (num%x!=0)
returnfalse;
elsereturntrue;
x=x=2;
}
num=num+2;
}
PS. when your done I'd love to see it if you would share.
In the program above there is two errors:
In main():
for (int i = 0; i < 50; i++)
should be corrected to:
for (int i = 2; i < 50; i++)
and in prime():
for (int d = 2; d < x/2; ++d)
should be corrected to:
for (int d = 2; d <= x/2; ++d)
or even better:
for (int d = 2; d <= sqrt(x); ++d)