Is my implementation of happy number OK

Ian Kelly ian.g.kelly at gmail.com
Fri May 1 11:03:32 EDT 2015


On Fri, May 1, 2015 at 2:27 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Rather than 10**7, how about trying (10**500 + 2). Is it happy?
>
> Using the Python code from Wikipedia:
> https://en.wikipedia.org/wiki/Happy_number
>
> SQUARE = dict([(c, int(c)**2) for c in "0123456789"])
> def is_happy(n):
>   while (n > 1) and (n != 4):
>     n = sum(SQUARE[d] for d in str(n))
>   return n == 1
>
>
> I can calculate whether n=10**500 + 2 is happy in less than a millisecond on
> my computer.

Not really the most exciting example, since the following number in
the sequence would be 5. But a random sequence of 500 non-zero digits
doesn't seem to take substantially longer.



More information about the Python-list mailing list