I need to find the maximum remainder for n
divided by any integer number from 1 to n
, and the denominator which this remainder is found with.
It seems that the asker decided to solve this in two steps. They wrote a function fun1
returning the maximum remainder and a function fun2
, which fed with the previously calculated remainder, returns the corresponding dividend.
While not an efficient approach, it could work if implemented correctly, but that's not the case.
Other than some (very) bad naming choices, we can find:
In the original version of the posted code, fun2
has a function prototype with a single parameter and it is called passing the value returned by fun1
, which is the maximum remainder. The problem is that this way the function has no way to know what was the original value of n
and actually declares a local n
, initialized to zero, so that the body of the loop for(int i = 1; i <= n; i++)
is never executed.
The actual version of this question shows a definition of fun2
with two parameters, that can't compile unless both the prototype and the call site are changed accordingly.
Assuming that the original n
and the remainder p
were succesfully passed to fun2
, there still would be another issue:
int fun2(int n, int p ) {
int c = 0, d = 0;
for(int i = 1; i <= n; i++) {
int num = n % i;
c = max(num, c);
if(c == p){ // So, if we reach the passed remainder...
break; // We break out of the loop, skipping...
}
d = i; // this line, meaning...
}
return d; // That the dividend previous to the correct one is returned!
}
They could just return i;
when c == p
.
The answer by The Dreams Wind presents a much better approach to this task. I'd like to suggest an O(1) solution, though. Consider these points:
The result of n % i
can't be equal or greater than i
. It's in the range [0, i)
.
n / 2
is the greatest number that can divide n
other than n
itself. It means that all the numbers i
in (n/2, n)
are such that n % i > 0
.
For every number i
in (n/2, n)
, we can actually say that n % i = n - i
.
So, when n
is greater than 2, the i
corresponding to the maximum remainder is just 1 + n/2
and said remainder is n - n/2 - 1
.