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)
returnfalse; // has a remainder
}
returntrue; // All divisors checked. None have remainders
}
// 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)
returnfalse; // has a remainder
}
returntrue; // 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.