# Re: Happy Numbers (#93)

**URL:** <https://www.ruby-forum.com/t/re-happy-numbers-93/67454>\
**Category:** Ruby\
**Created:** [September 4, 2006, 2:44pm UTC](https://www.ruby-forum.com/t/re-happy-numbers-93/67454 "2006-09-04T14:44:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![davidtl](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/35a633/32.png) [@davidtl](https://www.ruby-forum.com/u/davidtl)\
**Post date:** [September 4, 2006, 2:44pm UTC](https://www.ruby-forum.com/t/re-happy-numbers-93/67454/1 "2006-09-04T14:44:05Z")

</div>

Here is my simple solution, not thread safe, not optimize for finding  
happiest number between 2 numbers.

happy? method returns false if the number is unhappy or happy list if  
the number is happy.

class Integer  
def digits(base = 10)  
return [self] if self \< base  
self.divmod(base).inject { |div, mod| div.digits(base) \<\< mod }  
end

def happy?(base = 10)  
@@happy\_list = []  
\_happy?(base) ? @@happy\_list : false  
end

protected

def \_happy?(base)  
return false if @@happy\_list.include?(self)  
@@happy\_list \<\< self  
return true if self == 1  
self.digits(base).inject(0) { |n, d| n + d\*d }.\_happy?(base)  
end  
end

# some simple tests

if **FILE** == $0  
p 7.happy?  
p 37.happy?  
p 25.happy?(2) # base 2 is “happy base” all numbers(\>0) on base 2  
are happies.  
p 4394.happy?(16)  
p 367.happy?(100)  
end
