Greetings,
Well, you're right on. Finding the divisor of a positive number can be easily found using the modulus operator, %. The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second. In C++, the modulus operator is a percent sign, %. The syntax is exactly the same as for other operators:
int quotient = 7 / 3;
int remainder = 7 % 3; The first operator, integer division, yields 2. The second operator yields 1. Thus, 7 divided by 3 is 2 with 1 left over.
The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another: if x % y is zero, then x is divisible by y.
Now lets use this same principal by finding the divisor of 12. We know 1, 2, 3, 4, 6, and 12 are divisible by twelve. Maybe this can help us figure out how to determine the divisors using afor loop.
#include <stdio.h>
int main() {
int num = 12;
printf("The divisors of 12 are ");
for (trialDivisor = 1; trialDivisor <= num / 2; ++trialDivisor)
if (num % trialDivisor == 0) {
divisorSum += trialDivisor; // in other words: divisor_sum = divisor_sum + trial_divisor;
printf("%d ", trialDivisor);
}
return 0;
} This example is quite simple. You might ask yourself why we call the expressiontrialDivisor <= num / 2;. Well, I believe that is because 2 will always be a divisor of a positive number. It's usually dividend / divisor, and a divisor of 2 will never fail. Plus, we know that 24 is divisible into 24, though divisors only start at '/ 2' and down.
24 is divisbile by 12, 8, 6, etc...
36 is divisible by 18, 12, etc...
Hope this helps,
- Stack Overflow