I have to define a function where:
Starting with a positive integer
original, keep multiplyingoriginalbynand calculate the sum of all multiples generated includingoriginaluntil the sum is no longer smaller thantotal. Return the minimum number of multiplications needed to reach at value at or above the given total.
So for example:
multiply_until_total_reached (1,5,2)1*2=2, (1+2)<5, 2*2=4, (1+2+4)>5, 2 multiplications needed
multiply_until_total_reached (1,15,2)1*2=2, (1+2)<15, 2*2=4, (1+2+4)<15, 4*2=8, (1+2+4+8)=15, 3 multiplications
My current code works but the returned value is off by 1 in some cases. In a 1,1038,2 case, I get 9 multiplication needed instead of 10 but in the 1,15,2 case, I get the correct amount (3) multiplications.
Here's my code:
def multiply_until_total_reached(original, total, n):
if total < original:
return 0
elif total > original:
sumofdigits = 0 #declares var to keep track of sum of digits to compare to total
timesofmult = 0 #track how many multiplication operations
while sumofdigits <= total + 1:
multnum = original * n
sumofdigits = multnum + original
original = multnum
sumofdigits = sumofdigits + multnum
timesofmult = timesofmult + 1
return timesofmult
What's causing it to be off?
total == originalcase. You should probably haveif total <= original: return 0.O(log n)solution wherenrepresents the value oftotal.nlies between 0 and 1 and will not work at all ifnis negative. This solution is guaranteed to be correct for alln.