# Find whether a number is happy or not?

A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). Given a number print whether it is happy or unhappy.

Sample Inputs
7
4
13

Sample Outputs
Happy
Unhappy
Happy


Note: Your program should not take more than 10 secs for any number below 1,000,000,000.

## Ruby, 77 characters

a=gets.to_i;a=eval"#{a}".gsub /./,'+\&**2'until a<5
puts a<2?:Happy: :Unhappy

• Ok, so I kinda get how this works (Literally taking each number, splitting it and adding the square of each digit), but what's with the stop condition of (a < 5) and using (a < 2) to decide if it's happy or not? I don't question the validity, just the logic. Apr 25, 2011 at 22:42
• That is the same as a <= 4 and a <= 1. If the cycle has a 1 in it then it is happy, and if it has a 4 in it, then it is not happy. See the wikipedia section about the unhappy cycle. So once the value of a is 4 or less, he checks if a is -- the result of that is your answer. Apr 25, 2011 at 23:57

## C - 115

char b[1<<30];a;main(n){for(scanf("%d",&n);b[n]^=1;n=a)for
(a=0;a+=n%10*(n%10),n/=10;);puts(n-1?"Unhappy":"Happy");}


This uses a 230-byte (1GB) array as a bitmap to keep track of which numbers have been encountered in the cycle. On Linux, this actually works, and efficiently so, provided memory overcommitting is enabled (which it usually is by default). With overcommitting, pages of the array are allocated and zeroed on demand.

Note that compiling this program on Linux uses a gigabyte of RAM.

• Why would you need anywhere close to that amount of memory for this problem? Apr 25, 2011 at 20:32
• @Peter: I suppose the approach is to (naively) catch a cycle for any number in the allowed input range from 1 to 1,000,000,000. But I agree that in light of happy number theory, the only check necessary is if the number 4 is reached, because that's the only cycle that will ever occur. Apr 25, 2011 at 20:51
• I'm curious: why does compiling it require so much RAM? Apr 25, 2011 at 21:22
• Appears to work fine on Windows 7 with MSVC 10. Doesn't consume any notable amount of memory while compiling and only marks the array in the page file (something that sounds way safer than the story you linked about memory overcommitting suggests ;-)).
– Joey
Apr 25, 2011 at 22:11
• I love the naivety of this approach. And the abuse of for loops is beautiful. Apr 27, 2011 at 1:52

## Golfscript - 34 chars

~{0\{48-.*+}/}9*1="UnhH"3/="appy"


Basically the same as this and these.

The reason for 9 iterations is described in these comments (this theoretically returns correct values up to about 10^10^10^974 (A001273)).

f 1="Happy"
f 4="Unhappy"
f n=f$sum[read[c]^2|c<-show n] main=interact$f.read


### Golfscript, 49 43 41 40 39 chars

~{0\10base{.*+}/.4>}do(!"UnhH"3/="appy"


Every happy number converges to 1; every unhappy number converges to a cycle containing 4. Other than exploiting that fact, this is barely golfed at all.

(Thanks to Ventero, from whose Ruby solution I've nicked a trick and saved 6 chars).

## Python - 81 chars

n=input()
while n>4:n=sum((ord(c)-48)**2for c inn)
print("H","Unh")[n>1]+"appy"


Some inspiration taken from Ventero and Peter Taylor.

• better off doing a int(c) than ord(c)-48.... Apr 26, 2011 at 4:32

eTeX, 153

\let~\def~\E#1{\else{\fi\if1#1H\else Unh\fi appy}\end}~\r#1?{\ifnum#1<5
\E#1\fi~\s#1{0?}}~\s#1{+#1*#1\s}~~{\expandafter\r\the\numexpr}\message{~\noexpand


Called as etex filename.tex 34*23 + 32/2 ? (including the question mark at the end). Spaces in the expression don't matter.

EDIT: I got down to 123, but now the output is dvi (if compiled with etex) or pdf (if compiled with pdfetex). Since TeX is a typesetting language, I guess that's fair.

\def~{\expandafter\r\the\numexpr}\def\r#1?{\ifnum#1<5 \if1#1H\else
Unh\fi appy\end\fi~\s#1{0?}}\def\s#1{+#1*#1\s}~\noexpand


## Javascript (949287 86)

do{n=0;for(i in a){n+=a[i]*a[i]|0}a=n+''}while(n>4);alert(['H','Unh'][n>1?1:0]+'appy')


Input is provided by setting a to the number desired.

Credits to mellamokb.

• Save 1 char: n==4?h="Unh":n==1?h="H":a=n+""}alert(h+"appy") Apr 26, 2011 at 1:21
• @mella Thanks. I also shaved another char off by changing || to |. Apr 26, 2011 at 1:28
• Save 8 chars: Remove n==4?h.... Change to do...while loop with condition while(n>4). Then use this final statement instead: alert(["H","Unh"][n>1?1:0]+"appy") Apr 26, 2011 at 1:43
• @Mella Clever, I like it. Apr 26, 2011 at 2:01
• @Mella n needs to be defined before the while loop, I'm trying to think of how to not repeat n=0; Apr 26, 2011 at 2:08

## Python (98, but too messed up not to share)

f=lambda n:eval({1:'"H"',4:'"Unh"'}.get(n,'f(sum(int(x)**2for x inn))'))
print f(input())+"appy"


Way, way too long to be competitive, but perhaps good for a laugh. It does "lazy" evaluation in Python. Really quite similar to the Haskell entry now that I think about it, just without any of the charm.

## dc - 47 chars

[Unh]?[[I~d*rd0<H+]dsHxd4<h]dshx72so1=oP[appy]p


Brief description:

I~: Get the quotient and remainder when dividing by 10.
d*: Square the remainder.
0<H: If the quotient is greater than 0, repeat recursively.
+: Sum the values when shrinking the recursive stack.

4<h: Repeat the sum-of-squares bit while the value is greater than 4.

## Befunge, 109

Returns correct values for 1<=n<=109-1.

v v              <   @,,,,,"Happy"<      >"yppahnU",,,,,,,@
>&>:25*%:*\25*/:#^_$+++++++++:1-!#^_:4-!#^_10g11p  # J, 56 'Happy'"_('Unhappy'"_)([:$:[:+/*:@:"."0@":)@.(1&<+4&<)


A verb rather than a standalone script since the question is ambiguous.

Usage:

   happy =: 'Happy'"_('Unhappy'"_)([:$:[:+/*:@:"."0@":)@.(1&<+4&<) happy =: 'Happy'"_('Unhappy'"_)([:$:[:+/*:@:"."0@":)@.(1&<+4&<)
happy"0 (7 4 13)
happy"0 (7 4 13)
Happy
Unhappy
Happy


## Scala, 145 chars

def d(n:Int):Int=if(n<10)n*n else d(n%10)+d(n/10)
def h(n:Int):Unit=n match{
case 1=>println("happy")
case 4=>println("unhappy")
case x=>h(d(x))}

• Wouldn't (n*n) be shorter as n*n , or does whitespace not suffice to separate an if-expression from the else? Apr 27, 2011 at 11:50
• Yes, I did so, Peter. Apr 27, 2011 at 12:07
• Here is a 126 bytes tail-recursive version, without pattern matching: def h(s: String):String=if(s=="1")"H"else if(s=="4")"Unh"else h(s.map(_.asDigit).map(a=>a*a).sum+"");print(h(readLine)+"appy") Oct 21, 2017 at 13:56
• @6infinity8: Why don't you post it as a new answer? Oct 21, 2017 at 19:00
• The initial post is old; I was just trying to improve your solution. Oct 21, 2017 at 20:38

# J (50)

'appy',~>('Unh';'H'){~=&1$:@.(>&6)@(+/@:*:@:("."0)@":)  I'm sure a more competent J-er than I can make this even shorter. I'm a relative newb. New and improved: ('Unhappy';'Happy'){~=&1$:@.(>&6)@(+/@:*:@:("."0)@":)


Newer and even more improved, thanks to ɐɔıʇǝɥʇuʎs:

(UnhappyHappy){~=&1$:@.(>&6)@(+/@:*:@:("."0)@":)  • You can get a character by not splitting out 'appy'. I think you can also remove the parentheses aroundd ("."0) - adverbs bind tighter than conjunctions. Apr 27, 2011 at 5:36 • I can't remove the parentheses around ("."0). That produces a rank error, but if I don't split 'Happy' and leave the result boxed, I can save a character. Apr 28, 2011 at 20:12 • The reason I can't leave out the parentheses around ("."0) is that conjunctions apply to the entire preceding train of verbs to which they're attached, which is not what I want. If I say +/@:("."0)@":, that is very different from +/@:"."0@:, which is actually (+/@:".)"0@:. May 1, 2011 at 15:55 • A massive necro, but you could save 4 chars by replacing 'Unhappy';'Happy' with UnhappyHappy. Dec 15, 2014 at 7:39 • @ɐɔıʇǝɥʇuʎs That works, but where is it documented that you can skip the quoting of strings with ? Dec 15, 2014 at 10:50 # Python (91 characters) a=lambda b:b-1and(b-4and a(sum(int(c)**2for c inb))or"Unh")or"H";print a(input())+"appy"  # Common Lisp 138 (format t"~Aappy~%"(do((i(read)(loop for c across(prin1-to-string i)sum(let((y(digit-char-p c)))(* y y)))))((< i 5)(if(= i 1)"H""Unh"))))  More readable: (format t "~Aappy~%" (do ((i (read) (loop for c across (prin1-to-string i) sum (let ((y (digit-char-p c))) (* y y))))) ((< i 5) (if (= i 1) "H" "Unh"))))  Would be shorter to just return "Happy" or "Unhappy" right from the (do), but arguably that wouldn't count as a whole program # K, 43 {{$[4=d:+/a*a:"I"$'$x;unhappy;d]}/x;happy}


# Jelly, 17 bytes

D²SµÐLỊị“¢*X“<@Ḥ»


Try it online!

### How?

D²SµÐLỊị“¢*X“<@Ḥ» - Main link: n
µÐL            - loop while the accumulated unique set of results change:
D                 -   cast to a decimal list
²                -   square (vectorises)
S               -   sum
- (yields the ultimate result, e.g. n=89 yields 58 since it enters the
-  "unhappy circle" at 145, loops around to 58 which would yield 145.)
Ị           - insignificant? (abs(v)<=1 - in this case, 1 for 1, 0 otherwise)
“¢*X“<@Ḥ» - dictionary lookup of ["Happy", "Unhappy"] (the central “ makes a list)
ị          - index into
- implicit print


# C++ 135 , 2 Lines

#include<iostream>
int n,i,j;int main(){for(std::cin>>n;n>1;n=++j&999?n*n+i:0)for(i=0;n/10;n/=10)i+=n%10*(n%10);std::cout<<(n?"H":"Unh")<<"appy";}


This is a modified version of the one I did here:

https://stackoverflow.com/questions/3543811/code-golf-happy-primes/3545056#3545056

• What is the &999 do? And how does it work if j is a garbage value? Apr 11, 2014 at 13:44
• @Dgrin91, I wrote this 3 years ago, so i can't remember exactly how it works. I think the &999 makes the statement if(j==999){n = 0;}else{n=n*n +i;}, j shouldn't be a garbage value, globals are zero initialized. Apr 14, 2014 at 9:18

Yes, this challenge has three years; yes, it already has a winner answer; but since I was bored and done this for another challenge, thought I might put it up here. Surprise surprise, its long - and in...

# Java - 280 264 bytes

import java.util.*;class H{public static void main(String[]a){int n=Integer.parseInt(new Scanner(System.in).nextLine()),t;while((t=h(n))/10!=0)n=t;System.out.print(t==1?"":"");}static int h(int n){if(n/10==0)return n*n;else return(int)Math.pow(n%10,2)+h(n/10);}}


Ungolfed:

import java.util.*;

class H {

public static void main(String[] a) {
int n = Integer.parseInt(new Scanner(System.in).nextLine()), t;
while ((t = h(n)) / 10 != 0) {
n = t;
}
System.out.print(t == 1 ? "" : "");
}

static int h(int n) {
if (n / 10 == 0) {
return n * n;
} else {
return (int) Math.pow(n % 10, 2) + h(n / 10);
}
}
}


# C# 94 bytes

int d(int n)=>n<10?n*n:(d(n%10)+d(n/10));string h(int n)=>n==1?"happy":n==4?"unhappy":h(d(n));


For any given number (as int), h() will return the correct value. You can try the code on .NetFiddle.

Kudos to user unknown for the original algorithm.

## Clojure, 107 97 bytes

Update: Removed unnecessary let binding.

#(loop[v %](case v 1"Happy"4"Unhappy"(recur(apply +(for[i(for[c(str v)](-(int c)48))](* i i))))))


Original:

#(loop[v %](let[r(apply +(for[i(for[c(str v)](-(int c)48))](* i i)))](case r 1"Happy"4"Unhappy"(recur r))))


First time using a nested for :o

# R, 117 91 bytes

-16 bytes thanks to Giuseppe

a=scan();while(!a%in%c(1,4))a=sum((a%/%10^(0:nchar(a))%%10)^2);if(a-1,'unhappy','happy')

• Use strtoi instead of as.numeric and paste instead of as.character, but there is a shorter approach to get the digits. If you use if(a-1,"unhappy","happy") instead that should save another byte. Finally, you can make this anonymous to shave off a few more bytes. Oct 19, 2017 at 16:40

# Julia 1.5 , 188 bytes (without indent)

f(s)=sum([parse(Int64,i)^2 for i in string(s)])
function g(s)
a=[f(s)]
while true;h=f(last(a))
if h in a
println("unhappy")
break
elseif h==1
println("Happy")
break
end
append!(a,h)
end
end


Try it online!