Find the next divisor without remainder

7.5k Views Asked by At

I divide a value and if the remainder is not 0 I want the closest possible divisor without remainder.

Example:

I have:
$100 \% 48 = 4$

Now I am looking for the next value which divide 100 wihtout remainder. Result: $50$
$100 \% 50 = 0%$

Just another example:
$14 \% 6 = 2$
Result $7$
$14 \% 7 = 0$

Does anyone know how to calculate this?

2

There are 2 best solutions below

3
On BEST ANSWER
  1. Calculate 100%48. If the answer is zero, stop. Otherwise:
  2. Calculate 100%49. If the answer is zero, stop. Otherwise:
  3. Calculate 100%50. If the answer is zero, stop. Otherwise:

etc.

0
On

I had the same question when I found this, so here's some sample (python) code that would find the nearest divisor with no remainder.

Num = 636         # Numerator we are seeking to divide with no remainder
Den = 8           # Initial denominator
max_iters = 15    # caps the maximum loops
iters = 1         # initialize counter
Deni = Dend = Den # vars for searching increasing and decreasing denominators

while Num%Den != 0:
Deni +=1                 # searching increased vals
if Dend > 0 : Dend -=1   # searching decreased vals, but check 0 condition
if Num%Dend ==0:         # found a 0 remainder denominator
    Den = Dend           # assign found denominator
    break
elif Num%Deni ==0:       # found a 0 remainder denominator
    Den = Deni           # assign found denominator
    break
elif iters >= max_iters: # check loop count
    break
iters+=1

Not as clean as a built in function, but hopefully it helps the next person.