gusgxrha gusgxrha - 1 year ago 59
C Question

How often is a number divisible without a rest?

I am currently trying to write a method which checks how often a number is divisible by 5 with a rest of 0 (e.g. 25 is two times; 125 is three times).

I thought my code is correct but it always states that it is possible one more time than it actually is (e.g. 25 is three times; wrong).

My approach is the following:

int main()
div_t o;
int inp = 25, i = 0;
while(o.rem == 0){
o = div(inp, 5);
inp = o.quot;
return 0;

I debugged the code already and figured that the issue is that it steps once more into the loop even though the rest is bigger 0. Why is that? I can't really wrap my head around it.

First: 25/5 = 5; Rest = 0;
Second: 5/5 = 1; Rest = 1; - Shouldn't it stop here?
Third: 1/5 = 0; Rest = 1;

Ah... got it. The point where the remainder is 0 is reached when the division is done with the number which results in a rest bigger zero which is after i got increased.

What is the cleanest approach to fix that? i -= 1 seems kinda like a workaround and I wanted to avoid using an if to break

Answer Source

Change the while loop condition in :

while(o.rem == 0 && inp >= 5) 

In this way your division will stop after that you are inspecting the number 5.

A suggestion: use a const variable to wrap the 5 ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download