Generalising condition in if statement

I want to write an if statement which has condition like
1
2
3
4
if(i%1==0 && i%2==0 && i%3==0 && i%4==0 && i%5==0 && 
i%6==0 && i%7==0 && i%8==0 && i%9==0 && i%10==0 &&
 i%11==0 && i%12==0 && i%13==0 && i%14==0 && i%15==0 
&& i%16==0 && i%17==0 && i%18==0 && i%19==0 && i%20==0)

This of course is not the right way to write it. Please help me to generalise it so that I can check the condition not only till 20 but till any number without manually adding all conditions.
Use a loop. Easiest if you put the loop in a function.

1
2
3
4
5
6
7
8
9
//  i = number to check 
//  n = Number of divisors to check   
bool test_number (int i, int n)
{  for (int j=1; j<=n; j++)
    {    if ( i%j != 0)
            return false;  // has a remainder
    }
    return true;  // All divisors checked.  None have remainders 
}

Unrelated note:

1
2
//  i = number to check 
//  n = Number of divisors to check    


If you find yourself adding comments to explain what your variables are... you probably need to rename your variables.

1
2
3
4
5
6
7
8
9
bool test_number (int numberToTest, int divisorCount)
{
    for (int i=1; i<=divisorCount; i++)
    {
        if ( numberToTest % i != 0)
            return false;  // has a remainder
    }
    return true;  // All divisors checked.  None have remainders 
}


'test_number' also isn't the greatest name. But I'm too lazy to come up with a better one.


The point is: don't underestimate the importance of good names.
Last edited on
Topic archived. No new replies allowed.