### Checking if a variable is an integer

Hello,
I am now to C++ (I started yesterday), and I am trying to make a program that spits out prime numbers. My method is to divide an odd number by every number less than one half that number and see if the result is an integer or not. This requires me to check if a variable is an integer. Is this possible?

Here's the code. I have put "y!=an integer" in the places where I need to check if y is an integer.

#include <iostream>
using namespace std;

int main()
{
int n=1, x;
double y;
NewNumber:
y=0.5;
for (x=2; y!=an integer, x<(n/2); x++) y=n/x;
if (y!=an integer) {
n=n+2;
goto NewNumber;
}
else {
n=n+2;
cout << n << "\n";
goto NewNumber;
}
return 0;
}

Last edited on
closed account (LN7oGNh0)
'Integer' has not been declared as an 'int'. This means the compiler will not know what 'integer' is. If you want to check if the number is a whole number, than you should try and check if the number has an no remainder.

so use the remainder operator. (modulus): `%`

This will make sure that the number has no remainder an therefore cannot be a decimal.

Hoped that helped!
Good idea! I'll try that out now.
Hm, I keep getting the error message "Invalid operands to binary expression."
I googled it, but I'm still sure what it means.
this is what I've done:

for (x=2, a = (y%1); a!=0, x<(n/2); x++) y=n/x;

EDIT: OK, i just realized this wouldn't work anyway, because a would always be zero.
Last edited on
% can only be used on two integers and gives you the remainder from the division of the two integers. http://en.wikipedia.org/wiki/Remainder

When / is used on two integers the result will be an integer (fractional part discarded). If you want / to give you a double make sure that at least one of the operands to / is of type double. You can do that with a cast.
`y = static_cast<double>(n) / x;`
One way to check if y is an integer is to see if y is equal to y rounded down to closest integer.
`y == std::floor(y)`

You can use % but then you have to use it on n and x. If the remainder of the division between n and x is 0, n is divisible by x;
`(n % x) == 0`

EDIT: fixed mistake with how I used %.
Last edited on
^ Thank you, thank you!
Congratulations and welcome!

 My method is to divide an odd number by every number less than one half that number

Actually, you don't need to do that because, 1/2 any number would give you the result of 2.

To find whether X is a prime number you only look for numbers less or equal to sqrt(X).
Last edited on
Topic archived. No new replies allowed.