3

I have an expression of n like (30 - n(n - 1)) / 2n. And I want search the possible n which will be my answer only when the result is an integer. Is there any way to decide whether the result of this expression is an integer or not.

The only way that I can come up with is(in pseudo code ) :

for float n <- 1 to 100
  do float result = expression(n);
     int part = (int) result;
     if ( result - part < EPS )
       then good to go
3
  • Why do you declare n as a float ? Commented Aug 21, 2013 at 8:22
  • because if it is an int, the expression will be an ineger. Am I wrong? Commented Aug 21, 2013 at 8:23
  • Sure but then you can use integer remainder to see if the division in exact ! Commented Aug 21, 2013 at 8:24

3 Answers 3

7

You can use % to compute the remainder.

int denom = 2 * n;
int numer = 30 - n * (n - 1);

if (denom) {
    if (numer % denom == 0) {
        then good to go
    }
} else {
    /*...denominator is 0! */
}
Sign up to request clarification or add additional context in comments.

2 Comments

That won't work so well for n == 0 :-) But since OP stated n ranges from 1 to 100, it doesn't really matter.
A divide by 0 exception is as good as an assertion, but you are right that it would be friendlier to test for a non-zero denominator.
2

if (30 - n(n - 1)) mod 2n equals to zero

Comments

1

If modf returns 0.0, the floating point number it is called on is an integer. This is the standard way of testing whether a floating point number is an integer; it works with all floating point values, even those that would overflow an int.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.