Function Repository Resource:

HappyNumberQ

Source Notebook

Test whether an integer is a happy number

Contributed by: Sander Huisman

ResourceFunction["HappyNumberQ"][n]

tests whether repeatedly summing up the square of the digits of n reaches 1.

ResourceFunction["HappyNumberQ"][n,b]

considers the integer digits of n in base b.

ResourceFunction["HappyNumberQ"][n,b,p]

raises the digits to the power p.

Details and Options

The base b has to be at least 2.
The power p has to be at least 1.

Examples

Basic Examples (2) 

Test whether 19 is a happy number:

In[1]:=
ResourceFunction["HappyNumberQ"][19]
Out[1]=

Test whether 1579 is a happy number based on its digits in base 7:

In[2]:=
ResourceFunction["HappyNumberQ"][1579, 7]
Out[2]=

Scope (1) 

Cube the numbers rather than squaring them:

In[3]:=
ResourceFunction["HappyNumberQ"][1579, 10, 3]
Out[3]=

Properties and Relations (1) 

In base 2, all numbers are happy:

In[4]:=
AllTrue[Range[10000], ResourceFunction["HappyNumberQ"][#, 2] &]
Out[4]=

Possible Issues (2) 

The negative sign in a negative number is ignored:

In[5]:=
ResourceFunction["HappyNumberQ"][Range[1000]] === ResourceFunction["HappyNumberQ"][-Range[1000]]
Out[5]=

Checking for higher powers can take a lot more time:

In[6]:=
AbsoluteTiming[ResourceFunction["HappyNumberQ"][999, 10, 60]]
Out[6]=

Neat Examples (2) 

Find numbers that are happy in many bases:

In[7]:=
data = Table[{n, b, ResourceFunction["HappyNumberQ"][n, b]}, {n, Range[2, 1000]}, {b, 2, 30}];
data = DeleteCases[data, {_, _, False}, \[Infinity]];
data = {#[[1, 1]], #[[All, 2]]} & /@ data;
data = TakeLargestBy[data, Length@*Last, 10];
Grid[Prepend[data, {"Number", "Bases in which it is happy"}]]
Out[11]=

Find happy numbers that are also prime:

In[12]:=
Select[Range[1000], PrimeQ[#] \[And] ResourceFunction["HappyNumberQ"][#] &]
Out[12]=

Publisher

SHuisman

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 10 May 2019

License Information