Discussion Locked

What is my two logic errors?

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

// Total the square of every 3rd number from 1 to 25
// Sum every 4th number from 1 to 25

int num;
int total_squared = 0;
int total_summed = 0;

for (num = 1; num < 25; num++)
if (num % 4)
total_squared = total_squared + (num * num);
if (num % 3)
total_summed = total_summed + num;

3 replies

by medievaldude

First of all, your logic is backwards. You need to use the mod (%) 3 with the num * num since you square every 3rd number. You need the mod 4 with the sum. Also, since mod gets you the remainder, you want to check that num % x is 0. Then you know you're on a number exactly divisible by x, where x is either 3 or 4, depending on what you want. Here's the code I think you should be using (I hope you read the explanation so that you understand the logic and can recreate something similar in the future). Please note that I have num <= 25 because I'm assuming you want to include the number 25 in your loop, even though it really won't matter in this case since 25 isn't exactly divisible by 3 or 4. Post back if you have problems.

for (num = 1; num <= 25; num++)
if ((num % 3) == 0)
total_squared = total_squared + (num * num);

if ((num % 4) == 0)
total_summed = total_summed + num;

This discussion is closed to new replies.