[Question]
  [
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.
  
[Answer]
## Ruby, 77 characters
```
a=gets.to_i;a=eval"#{a}".gsub /./,'+\&**2'until a<5
puts a<2?:Happy: :Unhappy
```
[Answer]
## 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](http://opsmonkey.blogspot.com/2007/01/linux-memory-overcommit.html) 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.
[Answer]
## Golfscript - 34 chars
```
~{0\`{48-.*+}/}9*1="UnhH"3/="appy"
```
Basically the same as [this](https://stackoverflow.com/questions/3543811/code-golf-happy-primes/3556849#3556849) and [these](http://golf.shinh.org/p.rb?happy%20number#GolfScript).
The reason for 9 iterations is described in [these comments](https://stackoverflow.com/questions/3543811/code-golf-happy-primes/3544162#3544162) (this theoretically returns correct values up to about `10^10^10^974` ([A001273](http://oeis.org/A001273))).
[Answer]
## Haskell - 77
```
f 1="Happy"
f 4="Unhappy"
f n=f$sum[read[c]^2|c<-show n]
main=interact$f.read
```
[Answer]
### 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).
[Answer]
## Python - 81 chars
```
n=input()
while n>4:n=sum((ord(c)-48)**2for c in`n`)
print("H","Unh")[n>1]+"appy"
```
Some inspiration taken from Ventero and Peter Taylor.
[Answer]
**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
```
[Answer]
## Javascript (~~94~~ ~~92~~ ~~87~~ 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.
[Answer]
## 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 in`n`))'))
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.
[Answer]
## 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.
[Answer]
## Befunge, 109
Returns correct values for 1<=n<=109-1.
```
v v              <   @,,,,,"Happy"<      >"yppahnU",,,,,,,@
>&>:25*%:*\25*/:#^_$+++++++++:1-!#^_:4-!#^_10g11p
```
[Answer]
# 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  
```
[Answer]
## 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))}
```
[Answer]
# 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:
```
(Unhappy`Happy){~=&1`$:@.(>&6)@(+/@:*:@:("."0)@":)
```
[Answer]
# Python (91 characters)
```
a=lambda b:b-1and(b-4and a(sum(int(c)**2for c in`b`))or"Unh")or"H";print a(input())+"appy"
```
[Answer]
# 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
[Answer]
# K, 43
```
{{$[4=d:+/a*a:"I"$'$x;unhappy;d]}/x;`happy}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
D²SµÐLỊị“¢*X“<@Ḥ»
```
**[Try it online!](https://tio.run/nexus/jelly#@@9yaFPwoa2HJ/g83N31cHf3o4Y5hxZpRQApG4eHO5Yc2v3//39LKDAFAA "Jelly – TIO Nexus")**
### 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
```
[Answer]
# [Perl 5](https://www.perl.org/), 62 + 1 (`-p`) = 63 bytes
```
$_=eval s/./+$&**2/gr while$_>1&&!$k{$_}++;$_=un x($_>1).happy
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ja1LDFHoVhfT19bRU1Ly0g/vUihPCMzJ1Ul3s5QTU1RJbtaJb5WW9saqLQ0T6FCAySuqZeRWFBQ@R8oqGerom@tmm2roWn934TL0JjL/F9@QUlmfl7xf11fUz0DQ4P/ugUA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'ŽØs[SnOD5‹#}≠i„unì}™
```
[Try it online](https://tio.run/##ASsA1P9vc2FiaWX//yfFvcOYc1tTbk9ENeKAuSN94omgaeKAnnVuw6x94oSi//83) or [verify the first 100 test cases](https://tio.run/##ATsAxP9vc2FiaWX/0YJFTsOQVj8iIOKGkiAiP/8nxb3DmHNbU25PRDXigLkjfeKJoGnigJ51bsOsfeKEov8s/w).
**Explanation:**
Each number will eventually result in either `1` or `4`, so we loop indefinitely, and stop as soon as the number is below 5.
```
'ŽØ                    '# Push string "happy"
   s                    # Swap to take the (implicit) input
    [       }           # Loop indefinitely
     S                  #  Convert the integer to a list of digits
      n                 #  Square each
       O                #  Take the sum
        D5‹#            #  If this sum is smaller than 5: stop the infinite loop
             ≠i    }    # If the result after the loop is NOT 1:
               „unì     #  Prepend string "un" to string "happy"
                    ™   # Convert the string to titlecase (and output implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'ŽØ` is `"happy"`.
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
f=lambda n:n>4and f(sum(int(d)**2for d in`n`))or("H","Unh")[n>1]+"appy"
```
[Try it online!](https://tio.run/##FcyxCoMwFAXQuX7F4015NotWKAh17g90EsFICAbqTUjt4NfHuB9OPPY1oM3Zvb5mW6wh9Bg6A0tO/f6b8tiVlbpuXUhkyWPGLBKS4jdr/mBlGTE0051NjAfni/nCaHxq6jQ1j6mvbjGVp4xe8gk "Python 2 – Try It Online")
...or, for the same byte count:
```
f=lambda n:n>4and f(eval('**2+'.join(`n*10`)))or("H","Unh")[n>1]+"appy"
```
[Try it online!](https://tio.run/##DcxBCsIwEADAs75i2UuzaRBTC0LBnv2Ap1LoSg1dqZsQitDXR@cBk/ZtidqUEm4rf54zg3bat6wzBPP68moqa5u6Or2jqJnU@vNERDEbvKPDhy5Ig/Z@rJFT2rGEmEFAFIarg9aBv4zd8ZCy6PYfhcoP "Python 2 – Try It Online")
[Answer]
# Perl 5 - 77 Bytes
```
{$n=$_*$_ for split//,$u{$n}=$n;exit warn$/.'un'[$n==1].'happy'if$u{$n};redo}
```
$n is the input value
[Answer]
# 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>
[Answer]
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);
        }
    }
}
```
[Answer]
# 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](https://dotnetfiddle.net/piCL9v).
Kudos to [user unknown](https://codegolf.stackexchange.com/users/373/user-unknown) for the original [algorithm](https://codegolf.stackexchange.com/a/2286/15214).
[Answer]
## 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
[Answer]
# 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')
```
[Answer]
# 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!](https://tio.run/##XY5BDsIgEEXXzimwK0i6EG10hXvP0NRkVJBRpA3QqKdH2oUmLiaT@fPy8m@jI5SvnA2PQsXxwdsBQ9T84NO2qUkc18z0gREjz2IK5K8F7ASY0Z8T9Z5NN6BqJ0EHT0tOM7lfgVWGO4yJoxBAhtnJgDAURXKeV6O3OAzvSsApaLyDdlFPmFLyB/0h/gIlKGvJsbZiDsrkb8O2qXe13HSwuHKa//kD)
]