Python cycle to math formula

714 Views Asked by At

There is some code snippet written on python:

number = 5602004
accum = 0
while number:
    accum += (3 * (number % 10))
    number = int(number / 10)
    accum += (number % 10)
    number = int(number / 10)

So, cycle is working while variable number greater then 0. The question is: can this cycle be presented as math formula?

1

There are 1 best solutions below

0
On BEST ANSWER

The formulation is naturally a recurrence relation: $$f(n) = f \left( \left\lfloor \left\lfloor \frac{n}{10} \right\rfloor \big/ 10 \right\rfloor \right) + 3 (n \ \mathrm{mod}\ {10}) + (\left\lfloor \frac{n}{10} \right\rfloor \ \mathrm{mod} \ 10)$$

This, itself, is most naturally viewed mod $100$:

$$f(n) = f(\text{$n$ without its two rightmost digits}) + 3 \times \text{rightmost digit} + \text{next-rightmost digit}$$

If $n$ has evenly-many digits, then: take $n$ as a base $10$ string. Take the first, third, fifth… digits' sum. Take the second, fourth, sixth… digits' sum, and multiply by $3$. Add the two together.

If $n$ has odd-many digits, then just stick a $0$ on the front and pretend it has evenly-many.