Difference between revisions of "TADM2E 1.28"
From Algorithm Wiki
(Recovering wiki) |
|||
Line 11: | Line 11: | ||
return quotient; | return quotient; | ||
} | } | ||
+ | </pre> | ||
+ | |||
+ | ---- | ||
+ | -- [[User:Vale.rho|Vale.rho]] 00:02, 25 Feb 2015 | ||
+ | |||
+ | Initially I also thought the previous solution, but the final sentence of the text made me suspicious ("Find a fast way to do it."), so this is my solution: | ||
+ | |||
+ | <pre> | ||
+ | def divide(num, den): | ||
+ | quotient = 0 | ||
+ | quot_accumulator = 1 | ||
+ | den_accumulator = den | ||
+ | |||
+ | while num >= den: | ||
+ | if num < den_accumulator: | ||
+ | den_accumulator = den | ||
+ | quot_accumulator = 1 | ||
+ | |||
+ | num = num - den_accumulator | ||
+ | quotient = quotient + quot_accumulator | ||
+ | quot_accumulator = quot_accumulator + quot_accumulator | ||
+ | den_accumulator = den_accumulator + den_accumulator | ||
+ | |||
+ | return quotient | ||
</pre> | </pre> |
Revision as of 23:11, 24 February 2015
// Note: This only works for positive values! int divide(int numerator, int denominator) { int quotient = 0; while(numerator >= denominator) { numerator -= denominator; quotient++; } return quotient; }
-- Vale.rho 00:02, 25 Feb 2015
Initially I also thought the previous solution, but the final sentence of the text made me suspicious ("Find a fast way to do it."), so this is my solution:
def divide(num, den): quotient = 0 quot_accumulator = 1 den_accumulator = den while num >= den: if num < den_accumulator: den_accumulator = den quot_accumulator = 1 num = num - den_accumulator quotient = quotient + quot_accumulator quot_accumulator = quot_accumulator + quot_accumulator den_accumulator = den_accumulator + den_accumulator return quotient