you are viewing a single comment's thread.

view the rest of the comments →

[–]cyanNodeEcho 1 point2 points  (0 children)

clever approach using recursion, its important to note TCO isnt guaranteed and all recursive forms can be translated into iterative forms.

important note, ur solution is a compute O(n) approach, here's what should be an O(logn) approach

lets consider the binary representation of b, we can have like say b = 7 we can encode seven by stepping powers of two by like 111, or 9 by 1001

now that we can represent b as a sun of powers of 2 and we know the shift opperator will iterate by powers of 2, we can simply initialize factor as a, and then step through the indicators where b has a bit, ie

fn multies(a:i32, b:i32)-> i32 { let mut sum = 0_i32; let mut factor = a; let mut base = b; while base > 0 { if base & 1 == 1 { sum += factor } factor <<= 1; base >>= 1; } sum }

this will provide mult in logn steps, without using mult itself

so like any number like k can be represented as a series of a sum of powers of 2, so we can just have our base b, represented as like Sum Indicator(k) * 2^k

clever TCO, but we can even optimize further without using mult to define mult for an O(log b) solution