This program does n iterations to determine t..." />

Code Golf: Happy Primes?

GolfScript - 64 chars (works for 1) ~:@. {0\`{15&. *+}/}*1=!"happy sad "6/=@,{@\)%!

},,2=4*"non-prime"> This program does n iterations to determine the happiness of the number, which is very wasteful for large numbers, but code-golf is not about conserving resources other than characters. The prime test is similarly inefficient - dividing n by all the values from 1 to n inclusive and checking that there are exactly two values with zero remainder.So while it is theoretically correct, running with really large numbers is not practical on real computers GolfScript - 63 chars (fails for 1) ~:@9{0\`{15&. *+}/}*1=!

"happy sad "6/=@,2>{@\%! },!4*"non-prime.

– Marko Aug 23 '10 at 2:53 2 About dc: Wikipedia, manpage. – ShreevatsaR Aug 25 '10 at 1:20 1 this is hardcore – Jasconius Sep 13 '10 at 18:33.

Mathematica 115 108 107 102 100 99 91 87 Chars 87 characters PrintIfNestTrIntegerDigits@#^2&,#,9>1,Sad,Happy,IfPrimeQ@#," "," non-",prime& -- Mr.Wizard Da monkey learnt a few tricks (91 chars) Print IfNestPlus@@(IntegerDigits@ #^2) &, #, 9 > 1, Sad, Happy , IfPrimeQ@#, " ", " non-", prime & Invoke with %7 Edit 5 - 99 Chars/ Nine iterations is enough. Thanks @Nabb, @mjschultz h = Print IfNestPlus @@ (IntegerDigits@#^2) &, #, 9 > 1, "Sad ", "Happy " , IfPrimeQ@#, "", "non-", "prime" & Edit 4 - 100 Chars/ Same as Edit 3, replacing 10^2 by 99 (allowing 84 digits for input values) ... Thanks, @Greg h = Print IfNestPlus @@ (IntegerDigits@#^2) &, #, 99 > 1, "Sad ", "Happy " , IfPrimeQ@#, "", "non-", "prime" & Edit 3 - 102 Chars/ Reworked the loop again. It is interesting that the recursion depth until eventually reaching 1 is bounded by (15 + Number of digits of the argument).

See here So for numbers with less than 85 digits (I think this limit is pretty well into the OP's "Don't worry about handling big numbers" consideration) the following code works h = Print IfNestPlus @@ (IntegerDigits@#^2) &, #, 10^2 > 1, "Sad ", "Happy " , IfPrimeQ@#, "", "non-", "prime" & I changed the "NestWhile" for the shorter "Nest", and so, instead of specifying a stop condition for the recursion, is enough to hardcode the desired recursion depth (10^2). It is not very efficient, but that's the golfer's life :D Edit 2 - 107 Chars/ Reworked the Sad/Happy assignment h = Print IfNestWhilePlus @@ (IntegerDigits@#^2) &, #, # > 4 & > 1,"Sad ","Happy " ,IfPrimeQ@#, "", "non-" , "prime" & All spaces/newlines except on literals are optional and added for readability Explanation: The NestWhilePlus @@ (IntegerDigits@#^2) &, #, # > 4 & Recurses applying "function" Add up sum of digits squared until the result is 4 or less. The function has the property that it stagnates at "1", or enters the cycle {4, 16, 37, 58, 89, 145, 42, 20, 4, ...}.

So, when the outcome is "1", the number is "Happy" and when the outcome is "4", it is "Sad". If the result is "2", the number is also SAD, because it'll enter the SAD cycle in the next iteration (2^2 = 4). If the result is 3, the cycle is 3->9->81->65->61->37->58->89->145-> .... (Enters the SAD loop).

So, we can stop the recursion when the result is 4 or less, knowing that only a result of "1" will lead to a Happy number. Perhaps other solutions may take advantage of this fact. In fact, the results 5 and 6 also lead to SAD numbers, but that gives us only an efficiency boost and not a golfing advantage (I guess).

Edit 1 - 108 Chars/ Reworked the Loop Control logic h = Print NestWhilePlus@@(IntegerDigits@#^2) &, #, #>4 & /. {1 →"Happy ",_→"Sad "} , IfPrimeQ@#, "", "non-" , "prime" & Original - 115 Chars/ h = Print IfNestWhilePlus @@ (IntegerDigits@#^2) &, #, Unequal, All == 1 ,"Happy ", "Sad ", IfPrimeQ@#, "", "non-", "prime" & The statement NestWhilePlus @@ (IntegerDigits@#^2) &, #, Unequal, All performs the recursive application of the sums of the digits squared, until some value repeats. The "Unequal,All" part takes care of the comparison across the preceding values list.

Finally returns the repeated value, which is "1" for Happy Numbers. Sample run h7 Happy prime h2535301200456458802993406410753 Sad non-prime Looping (Slightly changing the Print statement) 1 Happy non-prime 2 Sad prime 3 Sad prime 4 Sad non-prime 5 Sad prime 6 Sad non-prime 7 Happy prime 8 Sad non-prime 9 Sad non-prime 10 Happy non-prime 11 Sad prime 12 Sad non-prime 13 Happy prime.

– Greg Aug 23 '10 at 15:35 1 @mjschultz The required depth is not a monotone function. For example, calculating h30 requires 11 iterations. The max depth value for numbers under 1000 is 15.

So, 9 is way toooo low. – belisarius Aug 23 '10 at 16:00 1 +1, nice explanation! – Alex.

S. Aug 23 '10 at 17:09 1 @mjschultz Here is the compiled version for running in the free Mathematica Player, and the instructions. Just in case.

Code.google. Com/p/magicnumbers/wiki/… – belisarius Aug 23 '10 at 18:56 2 @belisarius Your test condition is >1, i.e. Happy numbers will have reached 1, not unhappy numbers some arbitrary value.

The smallest values for n steps: s(5) = 7, s(6) = 356, s(7) = 78999. Logâ‚? ‚€(s(8)) ~ 975 (=78999/81).

Logâ‚? ‚€(logâ‚? ‚€(s(9))) ~ 974.

Logâ‚? ‚€(logâ‚? ‚€(logâ‚?

‚€(s(10)))) ~ 974. 9 iterations is therefore sufficient for everything up to 10^10^10^974, or 10^10^974 digits. I suppose I missed a step earlier.

– Nabb Aug 23 '10 at 20:18.

Python - 127 chars Beating both perl answers at this moment! L=n=input() while l>4:l=sum(int(i)**2for I in`l`) print'sad','happy'l1): I also ported this answer to GolfScript and it is just over 1/2 the size!

3 The slice trick is cool! – Roberto Bonvallet Aug 23 '10 at 20:05 4 I never knew a space isn't required before that first for. – vlad003 Aug 24 '10 at 1:04 1 +1 Never thought I'd see python beat perl in a terse contest.

Incidentally, not gzip, bzip2, or even xz can not compress this smaller than it already is. – Seth Aug 24 '10 at 5:06 2 @Seth: Most compression algorithms have some small amount of overhead and thus are miserable at compressing tiny files. – Brian Aug 24 '10 at 13:27.

C#, 380 378 374 372 364 363 315 280 275 274 Chars By replacing the recursive function with nested loops, I was able to bring the stroke count to a respectable 280 (100 less than the original). Class P{static void Main(stringa){var s=new System.Collections.Generic.HashSet();int n=int. Parse(a0),p=n>1?4:0,c,d=1;for(;++d1&s.

Add(n);n=c)for(c=0;n>0;c+=d*d,n/=10)d=n%10;System.Console. Write((n>1? "sad":"happy")+" non-prime".

Remove(1,p));}} Here it is with whitespace: class P { static void Main(string a) { var s = new System.Collections.Generic.HashSet(); int n = int. Parse(a0), p = n > 1? 4 : 0, c, d = 1; // find out if the number is prime while (++d 1 & s.

Add(n); n = c) for (c = 0; n > 0; c += d * d, n /= 10) d = n % 10; System.Console. Write( (n > 1? "sad" : "happy") + " non-prime".

Remove(1,p) ); } }.

4 +1 for "figure out happiness" – belisarius Aug 23 '10 at 20:37.

Python 2.6: 194 180 chars, 4 lines import re s=lambda n,l:0if n==1 else n in l or s(sum(int(a)**2for a in str(n)),l+n) n=input() print'happy','sad's(n,),'non-'*bool(re. Match(r'1? $|(11+?)\1+$','1'*n))+'prime' The lexer being able to split 0if and 2for into two tokens each was a nice surprise to me :) (it doesn't work with else though) Function s (sad) is recursive, and receives the list of previous numbers in the cycle as its second parameter.

Primality is tested inline using the regexp trick. By using the deprecated `n` syntax instead of str(n), one can further reduce the character count by 4 characters, but I choose not to use it.

1 That looks awesome :P. And if you replace your int(sys. Argv1) with input() it'll bring your char count down to 180.

– vlad003 Aug 23 '10 at 3:02 1 Thanks! I didn't notice stdin was allowed. – Roberto Bonvallet Aug 23 '10 at 3:09 1 Nice!

You beat my solution by 60 chars and 15 lines! – Chinmay Kanchi Aug 23 '10 at 3:26 3 +1, the regex for prime numbers is VERY nice! – yassin Aug 23 '10 at 4:03.

"sad":"happy",p>=C&C>1?"":"non-");}main(c){h(c,c,0,scanf("%d",&c));} $ . /a. Out 139 happy prime $ .

/a. Out 2 sad prime $ . /a.

Out 440 happy non-prime $ . /a. Out 78 sad non-prime This is one recursive function that never issues a return but either calls itself or prints output when it's done.

The recursive function sums squared digits and determines prime-ness in two for loops. The scanf returns 1 which is put as an argument to h(), saving one ; and one 1 (and at the cost of having to use prefix ++p instead of postfix p++ which would make p>C possible instead of p>=C) r&~5 is 0 for 1 4 5, of which 1 indicates happiness and the others sadness. Next attempt: drop h() and make main() recursive.

MATLAB 7.8.0 (R2009a) - 120 characters Whitespace, newlines, and comments added for readability n=input(''); s=n; c={'happy ','sad ','non-'}; while s>6, s=int2str(s)-48; s=s*s'; %'# Comment to fix code highlighting end; disp(c{s1 ~isprime(n)} 'prime').

It seems to cause invalid output when the input is 7. Would while s>6, work? – mjschultz Aug 23 '10 at 19:53.

Javascript 244 250 function h(n){p=n=nPush(n);k=""+n;n=0;for(i=0;iIndexOf(",1,")"":"non-";return w+"prime"} The above code should work in browsers without additional fancy functions and features (such as Array.prototype. IndexOf and notation for strings), but I haven't tested it outside of Firefox. Be aware that all but n are global variables (I'm just being cheap).

Usage h(139) // returns "happy prime.

2 Nice, I had to add a } at the end, but that is probably because I was using Firefox's Web Console. I'm impressed that Javascript and your code was able to handle h(2535301200456458802993406410753)! – mjschultz Aug 23 '10 at 13:07.

Ruby 1.9 169 168 146 chars h={1=>'happy'};s=->x{y=0;(y+=(x%10)**2;x/=10)while x>0;hy||(hy='sad';sy)} $>'happy'} is_happy = lambda do |number| #sum = number. Scan(/\d/). Reduce(0){|acum, digit| acum + digit.

To_i ** 2 } sum=0; while (number > 0) sum+= (number%10)**2 number/=10 end return hashsum if hashsum # If 1, or if cycled and hash contains the number already hsum = 'sad' return is_happy. Call(sum) end number = ARGV0. To_i string = "" string += is_happy.

Call(number) # either 'happy' or 'sad' string += is_prime(number)? " non-prime" : "prime" puts string Where the is_prime method is left as an exercise to the reader ;).

3 Nice use of regular expressions as primality check! – Gabe Aug 23 '10 at 0:37 1 You can save 1 character by getting rid of the () for that if statement (leaving a single space behind) as * is already higher precedence than =~. – shanna Aug 23 '10 at 7:51.

J: 113 characters h=.1=$:@(:+/:*:@". "0":)`@.(e. &1 4) 1!

:2&2;(({&('sad ';'happy '))@h,({&('non-prime';'prime'))@(1&p:))".(1! :13) $ echo -n 7 | jc happy. Ijs happy prime $ echo -n 139 | jc happy.

Ijs happy prime $ echo -n 2 | jc happy. Ijs sad prime $ echo -n 440 | jc happy. Ijs happy non-prime $ echo -n 78 | jc happy.

Ijs sad non-prime.

Python 2.6 happy. Py: 280 314 333 chars, 14 lines. Import re def q(z): while z!

=1:z=sum((int(a)**2 for a in `z`));yield z def h(g): l= while 1: try:z=g.next() except:return 'happy ' if z in l:return 'sad ' l. Append(z) p=lambda n:not re. Match(r'^1$|^(11+?)\1+$','1'*n) n=int(input()) print h(q(n))+'non-prime'4*p(n): Usage: $ echo 139 | python happy.

Py happy prime $ echo 2 | python happy. Py sad prime $ echo 440 | python happy.Py happy non-prime $ echo 1234567 | python happy. Py sad non-prime -- Readable version: import re, sys def happy_generator(z): while z!

= 1: z = sum((int(a)**2 for a in str(z))) yield z def is_happy(number): last = hg = happy_generator(number) while True: try: z = hg.next() except StopIteration: return True if z in last: return False last. Append(z) def is_prime(number): """Prime test using regular expressions :)""" return re. Match(r'^1?

$|^(11+?)\1+$', '1'*number) is None n = int(sys. Argv1) print "%s %sprime" % (('sad','happy')is_happy(n), ('non-','')is_prime(n)).

1 Couple of minor things I noticed at a brief glance: 1: while True == while 1. 2: Don't need a space after the final print statement. 3: Rename the ge function to a single char.

– sdolan Aug 23 '10 at 0:44.

Java: 294 286 285 282 277 262 260 chars Update 1: replaced BigInteger#isProbablePrime() by regex. Saved 8 chars. Update 2: replaced && by & (oops).

Saved 1 char. Update 3: refactored s a bit. Saved 3 chars.

Update 4: the test on n! =1 was superfluous. Saved 5 chars.

Update 5: replaced regex by for loop and refactored happy for loops little bits. Saved 15 chars. Update 6: replaced int/Integer by long/Long.

Saved 2 chars. Import java.util. *;class H{public static void main(Stringa){long n=new Long(a0),p=n>1?1:0,s,d=1;while(++d0;s+=d*d,n/=10)d=n%10;System.out.

Printf("%s %sprime",n>1? "sad":"happy",p>0? "":"non-");}} With newlines: import java.util.

*; class H{ public static void main(Stringa){ long n=new Long(a0),p=n>1?1:0,s,d=1; while(++d0;s+=d*d,n/=10)d=n%10; System.out. Printf("%s %sprime",n>1? "sad":"happy",p>0?"":"non-"); } }.

VBA 245 characters Good starter, will trim if time allows. Its only my 2nd go at code golf! Public Sub G(N) Dim Z, D, X, O X = N Z = N Do Until Z = 1 Or X > N Or X = 0 X = 0 For D = 1 To Len(CStr(Z)) X = X + CLng(Mid(CStr(Z), D, 1) ^ 2) Next D Z = X Loop If Z = 1 Then O = "Happy" Else O = "Sad" D = 2 Do If N / D = Int(N / D) Then O = O & " Not Prime": Debug.

Print O: Exit Sub D = D + 1 Loop While D.

2 I do golf challenges without regard to char count just to practice :P – Radu Aug 24 '10 at 15:12.

N:0;}i=1;w(m%++i&&j>1);std::cout" non-":" ")Also forgot to add that this assumes that there are no numbers with a sequence with over 0xFFFF numbers which a pretty sensible assumption. EDIT 2 fixed a bug. Rearranged to remove the excessive calls to std::cout.

MATLAB - 166 chars function happyprime(a) h={'non-prime','prime'}; h=h{isprime(str2num(a))+1}; for i=1:99 a=num2str(sum(str2num((a)'). ^2)); end s={'Sad ','Happy '}; s{(str2num(a)==1)+1},h Usage happyprime 139 ans = Happy prime.

F#, 249 chars let n=stdin.ReadLine()|>int let rec s x=seq{yield x;yield! String x|>Seq. SumBy(fun c->(int c-48)*(int c-48))|>s} printfn"%s %sprime"(if s n|>Seq.

Take 99|>Seq. Exists((=)1)then"happy"else"sad")(if2..n/2|>Seq. Exists(fun d->n%d=0)then"non-"else"").

Perl, 113 109 105 chars Beating all Python answers at this moment! SCNR. $n=$s=;$s=0,s/\d/$s+=$&*$&/ge while($_=$s)>4;die$s>1?

Sad:happy,$","non-"x(1x$n)=~/^1$|(^11+)\1+$/,prime.

1+"(apply str(repeat x\1)))"non-""")"prime"))) ptimac:clojure pti$ clj happy. Clj 139 CP=/Users/pti/playpen/clojure:/Users/pti/Library/Clojure/lib/clojure. Jar:/Users/pti/Library/Clojure/lib/jline.

Jar:/Users/pti/Library/Clojure/lib/clojure-contrib. Jar happy prime ptimac:clojure pti$ clj happy. Clj 440 CP=/Users/pti/playpen/clojure:/Users/pti/Library/Clojure/lib/clojure.

Jar:/Users/pti/Library/Clojure/lib/jline. Jar:/Users/pti/Library/Clojure/lib/clojure-contrib. Jar happy non-prime ptimac:clojure pti$ clj happy.

Clj 2 CP=/Users/pti/playpen/clojure:/Users/pti/Library/Clojure/lib/clojure. Jar:/Users/pti/Library/Clojure/lib/jline. Jar:/Users/pti/Library/Clojure/lib/clojure-contrib.

Jar sad prime ptimac:clojure pti$ clj happy. Clj 78 CP=/Users/pti/playpen/clojure:/Users/pti/Library/Clojure/lib/clojure. Jar:/Users/pti/Library/Clojure/lib/jline.

Jar:/Users/pti/Library/Clojure/lib/clojure-contrib. Jar sad non-prime I am leaning on the clojure contrib for the primes sequence. I wonder if using for loops would be shorter than recursion?

I read up on the regex prime number check. It's awesome and removes 30 chars and my dependency on clojure.contrib. I also refactored the command line parsing somwhat and inlined a function.

Pre golf(somewhat outdated): (defn hx m (cond (= x 1) "happy " (m x) "sad " :else (recur (reduce + (for n (map #(- (int %) 48) (str x)) (* n n))) (assoc m x 1)))) (println (let x (read) (str (h x{}) (if (re-matches #"^1$|^(11+)? \1+"(apply str(repeat x \1))) "non-" "") "prime"))).

Javascript, 192 190 185 182 165 158 chars The prime checking runs from 2 to square root of N. I wasted few chars there... In one line: for(x=2,y=m=n=prompt();x*xy? ' ':' non-')+'prime') Formatted: // Getting the number from the input and checking for primeness // (ie.

If after the loop x>y => n is prime) for (x=2, y=m=n=prompt(); x*xy? ' ' : ' non-') + 'prime') Check: jsfiddle.net/TwxAW/6.

PHP 217 Chars $t=$argv1;for($z=$t-1,$p=1;$z&&++$p"prime"; Usage: $ php -r '$t=$argv1;for($z=$t-1,$p=1;$z&&++$p"prime";' 139 happy prime.

Scala, 253 247 246 object H{def main(a:ArrayString){var s=Set(0) val n=a(0)toInt def r(m:Int):String={val k=""+m map(c=>c*(c-96)+2304)sum;if(k.

Python (285 270 269 246 241 247 240 237 chars, 21 20 21 18 19 lines) n=input() s='prime' for I in range(2,n): if n%i==0: s='non'+s break f=list(str(n)) g=set() while n! =1: n=sum(int(z)**2 for z in f) if n in g: s='sad '+s break else: f=list(str(n)) g. Add(n) else: s='happy '+s print s EDIT: Yes, the number went up, there was a bug :-P.

1 Rather than s='non'+s;break you can use s='non-prime' and save a few chars. – Gabe Aug 23 '10 at 4:17 1 vlad003: The break was only necessary because he was concatenating with the previous value. Since s='non-prime' is idempotent, there's no need for the break.

– Gabe Aug 23 '10 at 4:46.

Python 2.6, 300 298 294 chars Different from previous answer in that this doesn't use regex. I'm sure there's some way of shortening my h(x) function, but I'm still learning Python so I've got no idea. P(x) returns True if it's a non-prime.

H(x) returns True if it's happy. I've done the t = True so that it shortens the character count when doing the truth check. X=input() def p(x): if x==1 or 1 in 1 for I in range(2,x) if x%i==0: return True def h(x): l= while x not in l: l.

Append(x) x=sum(int(i)**2 for I in str(x)) if 1 in l: return True if h(x):print'happy', elif not h(x):print'sad', if p(x):print'non-prime' elif not p(x):print'prime.

Python, 169 168 158 157 166 164 162 chars, 4 lines l=n=input() while l>4:l=sum(int(i)**2for I in str(l)) print'sad','happy'l==1and str(n)! =1, print'non-',''n! =1 and sum(n%i==0for I in range(1,n))I could also shave off 6 chars by using backticks instead of the str-function, but let's play nice.

EDIT: Fixed a bug with 1 being a prime, which bumped up the charcount by 10. I figure there must be a more concise way than mine for doing this. EDIT 2: Apparently, python 2.6 allows print1, 2 without a space between the two.

EDIT 3: Used another calculation for the happy numbers.

Python - 142 chars I was playing around with this idea, but it turned out too long. Perhaps someone can find a way to make it shorter. Maybe it'll turn out better in Ruby.

Should be fun to understand how it works anyway :) n=input();L=n;print"%s non-prime"4*(1for f in range(1,n)if L. Append(sum(int(x)**2for x in`L-1`))or n%f.

GNU sed, 146 125 chars Run with sed -rf file. Using -r saves 5 backslashes. Needs bc, printf, and a shell with support for here-strings.

H s/^/printf %*s /e s/^ $|^( +)\1+$/non-/ s/ *$/prime/ x :a s/. /+&*&/g s//bc/+&*&/g s/. */echo 0&|bc/e tb :b s/^1$/happy/ s/^4$/sad/ Ta x s/^/yes|head -/e s/\n//g s/^y$|^(yy+)\1+$/non-/ s/y*$/prime/ x G s/\n/ / GNU sed, 134 115 chars (slightly bad formatted output) Slightly shorter version, doesn't respect output formatting (has extra spaces and a newline between happy/sad and (non-)prime).

H :a s/. /+&*&/g s//bc.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions