codefreak
codefreak

Reputation: 309

Happy numbers using python base 8

I have written a code that works for base 10
How to make it work for base 8??

SQUARE = dict([(c, int(c)**2) for c in "0123456789"])
def is_happy(n):
 s = set()
 while (n > 1) and (n not in s):
   s.add(n)
   n = sum(SQUARE[d] for d in str(n))
 return n == 1

a=is_happy(28)

Upvotes: 0

Views: 471

Answers (2)

Thanatos
Thanatos

Reputation: 44256

You just need to replace all the places in the algorithm where "base-10" is used with base 8. The only place this really is is when we turn the number into a string, so we can square each "digit". To determine digits, we need a base. Normally, we choose base 10, as your sample shows. Converting an integer to a string in an arbitrary base (or, in your case 8) has been answered here.

We might also adjust the lookup table SQUARE.

def to_base_8(n):
    digits = []
    while n > 0:
        digits.append(str(n % 8))
        n = n // 8
    return ''.join(reversed(digits))

SQUARE = dict([(c, int(c)**2) for c in "01234567"])
def is_happy(n):
 s = set()
 while (n > 1) and (n not in s):
   s.add(n)
   n = sum(SQUARE[d] for d in to_base_8(n))
 return n == 1

a=is_happy(28)

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

Use the octal representation instead.

n = sum(SQUARE[d] for d in oct(n))

Upvotes: 2

Related Questions