This program tests if a number is a prime or not. Although is shows the correct value for 5, 7, etc it doesn't show the correct answer for 2 and 3. Any advice?
I have an add function that receives two integral parameters and returns their sum, but it is not working! Here is my code:
1 2 3 4 5
int add(int a, int b)
{
int c = a + a - a + b - b + 4 * b - b - b - b + a;
return c;
}
I will not tell you
Remove the last addition, + a.
Instead, I will tell you
Just add the numbers inline. But if you insist on using a function, then just do this:
1 2 3 4
int add(int a, int b)
{
return a + b;
}
Now, back to the problem, why are you using global variables? Why doesn't your function return a Boolean value? Why didn't you call it is_prime or something along those lines?
bool is_prime(int n)
{
if (n < 2)
{
returnfalse;
}
if (n == 2)
{
returntrue;
}
if (n % 2 == 0)
{
returnfalse;
}
for (int i = 3; i * i <= n; i += 2)
{
if (n % i == 0)
{
returnfalse;
}
}
returntrue;
}
The input is the set of all integers. It returns false for any integer less than two. It returns false for every even integer besides two. It checks only odd integers up to the ceiling of the square root of the given integer (thanks to number theory, we have shown this to be or smallest upper bound).