Code Golf: Happy Primes!

Sunday, time for a round of golf!

Problem

Write the shortest source code by the number of characters to determine if the input number is “happy simple”, “rough simple”, “happy wrong”, or “rough non-simple”.

Enter

The input must be an integer that comes from a command line argument or stdin. Don't worry about working with large numbers, but do it if you can / want to. The behavior will be undefined for input values ​​less than 1, but 1 has a definite result.

Exit

The output should print the type of number: “happy right,” “sad simple,” “happy non-simple,” or “sad non-simple.” The final new line is optional.

Examples

$ happyprime 139 happy prime $ happyprime 2 sad prime $ happyprime 440 happy non-prime $ happyprime 78 sad non-prime 

Definitions

Just in case, your brain needs to be updated.

Lucky number

From Wikipedia,

A lucky number is determined by the following process. Starting with any positive integer, replace the number with the sum of the squares of its digits and repeat the process until the number is 1 (where it will stay), or it endlessly loops into a loop that does not include: 1. numbers, for of which this process ends with 1 are lucky numbers, and those that do not end with 1 are unlucky numbers (or sad numbers).

For example,

  • 139
  • 1 ^ 2 + 3 ^ 2 + 9 ^ 2 = 91
  • 9 ^ 2 + 1 ^ 2 = 82
  • 8 ^ 2 + 2 ^ 2 = 68
  • 6 ^ 2 + 8 ^ 2 = 100
  • 1 ^ 2 + 0 ^ 2 + 0 ^ 2 = 1

Main number

A prime number is an integer greater than 1 and has exactly two divisors: 1 and itself.

Happy prime

The lucky right number, therefore, is a number that is lucky and simple.

Answer selection

Obviously, the answer will be the shortest source code by the number of characters, which outputs the indicated results in all the cases that I am testing. I will mark the answer as soon as the next (community decides) a call to the golf code appears, so we can focus all our forces on this. :)

Decision

Well, it seems that a new golf code appeared in the city, and about a week has passed since the publication of this question, so the shortest source code (gnibbler 64 character Golfscript ) was noted as an answer. However, I liked both the 99-character Mathematica solution from belisarius and the critical 107-character dc solution from Nabb.

To others, great job! There have never been so many programming languages ​​on my computer. I hope everyone has learned new, dirty tricks for their favorite language.

Multiple

I republished part of the code created by this competition as an example for a script that I wrote to test different programs compared to the reference implementation for automatic classification . The README in this directory explains where the source code comes from, and states that all code is reused under the CC BY-SA 2.5 license (as indicated in the SO legal section ). Each directory is marked with your display name at the time of submission.

If you have a problem with reusing your code or attribution, let me know and I will fix the error.

+49
language-agnostic code-golf rosetta-stone
Aug 22 2018-10-22T00:
source share
33 answers
  • one
  • 2

GolfScript - 64 characters (works for 1)

 ~:@.{0\`{15&.*+}/}*1=!"happy sad "6/=@,{@\)%!},,2=4*"non-prime"> 

This program performs n iterations to determine the happiness of a number, which is very wasteful for large numbers, but code golf does not concern the conservation of resources other than characters. A simple test is also inefficient - dividing n by all values ​​from 1 to n inclusively and checking for exactly two values ​​with zero remainder. Therefore, although this is theoretically correct, working with really large numbers is not practical on real computers.

GolfScript - 63 characters (not executed 1)

 ~:@9{0\`{15&.*+}/}*1=!"happy sad "6/=@,2>{@\%!},!4*"non-prime"> 
+19
Aug 24 '10 at 13:22
source share

dc - 98 characters

 $ cat happyprimes [happy][sad]?dsI[[I~d*rd0<H+]dsHxd4<h]dshx[r]sr1=rP[ ][ non-]_1lI[1-d2>rdlIr%0<p]dspx-2=rP[prime]p $ echo 1 |dc happyprimes happy non-prime $ echo 139|dc happyprimes happy prime $ echo 2 |dc happyprimes sad prime $ echo 440|dc happyprimes happy non-prime $ echo 78 |dc happyprimes sad non-prime 
+67
Aug 23 '10 at 1:45
source share

Mathematica 115 108 107 102 100 99 91 87 Chars




87 characters

 Print[If[Nest[Tr[IntegerDigits@#^2]&,#,9]>1,Sad,Happy],If[PrimeQ@#," "," non-"],prime]& 

- Mr.Wizard




Yes, the monkey learned a few tricks (91 characters)

  Print[ If[Nest[Plus@@(IntegerDigits@ #^2) &, #, 9] > 1, Sad, Happy ], If[PrimeQ@#, " ", " non-"], prime ] & 

Call% [7]

Change 5 - 99 characters /

Nine iterations are enough. Thanks @Nabb, @mjschultz

 h = Print[ If[Nest[Plus @@ (IntegerDigits@#^2) &, #, 9] > 1, "Sad ", "Happy "] , If[PrimeQ@#, "", "non-"], "prime"] & 

Change 4 - 100 characters /

Same as Edit 3, replacing 10 ^ 2 with 99 (allowing 84 digits for input values) ... Thanks, @Greg

 h = Print[ If[Nest[Plus @@ (IntegerDigits@#^2) &, #, 99] > 1, "Sad ", "Happy "] , If[PrimeQ@#, "", "non-"], "prime"] & 

Edit 3 - 102 characters /

Recycled the loop again.

Interestingly, the depth of the recursion before reaching ultimately 1 is limited (15 + The number of digits of the argument). See here

So, for numbers with less than 85 characters (I think this limit is pretty well reflected in the OP “Don't worry about handling large numbers”), the following code works

 h = Print[ If[Nest[Plus @@ (IntegerDigits@#^2) &, #, 10^2] > 1, "Sad ", "Happy "] , If[PrimeQ@#, "", "non-"], "prime"] & 

I changed “NestWhile” for a shorter “socket”, and therefore, instead of specifying a stop condition for recursion, it’s enough to hardcode the desired recursion depth (10 ^ 2).

This is not very effective, but the life of a golfer: D

Change 2 - 107 characters /

Reworked Garden / Happy assignment

 h = Print[ If[NestWhile[Plus @@ (IntegerDigits@#^2) &, #, # > 4 &] > 1,"Sad ","Happy "] ,If[PrimeQ@#, "", "non-"] , "prime"] & 

All spaces / newlines except letters are optional and are added for readability.

Explanation:

  NestWhile[Plus @@ (IntegerDigits@#^2) &, #, # > 4 &] 

Recursions using the "function" [Add sum of digits to square] until the result reaches 4 or less. The function has the property that it stagnates to "1" or enters the cycle {4, 16, 37, 58, 89, 145, 42, 20, 4, ...}.

So, when the result is "1", the number is "Happy", and when the result is "4", it is "Garden".

If the result is “2”, it is also SAD, because it will go into the SAD loop at the next iteration (2 ^ 2 = 4).

If the result is 3, the cycle is 3-> 9-> 81-> 65-> 61-> 37-> 58-> 89-> 145-> .... (included in the SAD cycle).

Thus, we can stop recursion when the result is 4 or less, knowing that only the result "1" will result in a lucky number.

Perhaps other solutions can take advantage of this fact.

In fact, results 5 and 6 also lead to SAD numbers, but this only gives us an increase in efficiency and not an advantage in golf (I think).

Change 1 - 108 characters /

Reworked loop control logic

 h = Print[ NestWhile[Plus@@(IntegerDigits@#^2) &, #, #>4 &] /.{1"Happy ",_→"Sad "} , If[PrimeQ@#, "", "non-"] , "prime"] & 

Original - 115 characters /

 h = Print[ If[NestWhile[Plus @@ (IntegerDigits@#^2) &, #, Unequal, All] == 1 ,"Happy ", "Sad "], If[PrimeQ@#, "", "non-"], "prime"] & 

Statement

 NestWhile[Plus @@ (IntegerDigits@#^2) &, #, Unequal, All] 

performs recursive application of sums of numbers in a square until a certain value is repeated. The “Unequal, All” part compares the list of previous values. Finally returns a duplicate value that is "1" for Happy Numbers.

Run example

 h[7] Happy prime h[2535301200456458802993406410753] 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 
+29
Aug 23 '10 at 1:18
source share

Python - 127 characters

Beating both perl answers at this moment!

 l=n=input() while l>4:l=sum(int(i)**2for i in`l`) print['sad','happy'][l<2],'non-prime'[4*all(n%i for i in range(2,n))*(n>1):] 

I have also ported this answer to GolfScript and it is a little over 1/2 size!

+13
Aug 23 '10 at 18:13
source share

C #, 380 378 374 372 364 363 315 280 275 274 Chars

Replacing the recursive function with nested loops, I was able to bring the amount of stroke to a respectable 280 (100 less than the original).

 class P{static void Main(string[]a){var s=new System.Collections.Generic.HashSet<int>();int n=int.Parse(a[0]),p=n>1?4:0,c,d=1;for(;++d<n;)if(n%d<1)p=0;for(;n>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));}} 

Here is a space:

 class P { static void Main(string[] a) { var s = new System.Collections.Generic.HashSet<int>(); int n = int.Parse(a[0]), p = n > 1 ? 4 : 0, c, d = 1; // find out if the number is prime while (++d < n) if (n % d < 1) p = 0; // figure out happiness for (; n > 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) ); } } 
+12
Aug 23 2018-10-10T00:
source share

C, 188 187 185 184 180 172 171 165

 h(c,C,r,p){for(;C>1&&C%++p;);for(;c;c/=10)r+=c%10*(c%10);r&~5?h(r,C,0,1):printf( "%s %sprime",r-1?"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 return , but either calls or outputs when it is done. A recursive function sums square numbers and determines simplicity in two for loops. Scanf returns 1 , which is placed as an argument in h() , preserving one ; and one 1 (and by using the prefix ++p instead of postfix p++ , which will make p>C perhaps instead of p>=C )

r&~5 0 for 1 4 5 , of which 1 indicates happiness and the rest is sadness.

Next attempt: drop h() and make main() recursive.

+9
Aug 23 '10 at 0:16
source share

Python 2.6: 194 180 characters, 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, able to split 0if and 2for into two tokens, was a pleasant surprise for me :) (it does not work with else though)

Function s (sadly) is recursive and gets a list of previous numbers in the loop as a second parameter. Primality is tested inline with the regexp tag.

Using the legacy `n` syntax instead of str(n) , I can further reduce the number of characters by 4 characters, but I don't want to use it.

+9
Aug 23 '10 at 2:52
source share

Perl, 140 characters

 sub h{$_==1&& happy||$s{$_}++&& sad ||do{$m=0;$m+=$_**2for split//;$_=$m;&h}}$n=$_=pop; die h,$",(1x$n)=~/^1?$|^(11+?)\1+$/&&"non-","prime\n" 

Line breaks are optional.

+8
Aug 23 '10 at 1:23
source share

MATLAB 7.8.0 (R2009a) - 120 characters

Spaces, 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{[s<2 s>1 ~isprime(n)]} 'prime']) 
+7
Aug 23 '10 at 19:06
source share

Ruby 1.9

169 168 146 characters

  h={1=>'happy'};s=->x{y=0;(y+=(x%10)**2;x/=10)while x>0;h[y]||(h[y]='sad';s[y])} $><<s[n=$*[0].to_i]+" #{'non-'if '1'*n=~/^1?$|^(11+?)\1+$/}prime" 



If we use p instead of $><< , the code is reduced by 2 characters

Using:

$ ruby ​​happyprime.rb 139 happy prime $ ruby ​​happyprime.rb 2 sad prime




Not Golf:

 hash = {1->'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 hash[sum] if hash[sum] # If 1, or if cycled and hash contains the number already h[sum] = 'sad' return is_happy.call(sum) end number = ARGV[0].to_i string = "" string += is_happy.call(number) # either 'happy' or 'sad' string += is_prime(number) ? " non-prime" : "prime" puts string 

If the is_prime method is_prime left as an exercise for the reader;)

+5
Aug 22 '10 at 23:43
source share

Haskell 172

 hsn|n`notElem`s=h(n:s)$sum[read[k]^2|k<-show n]|1`elem`s="happy "|0<1="sad " cn|n<2||any((0==).mod n)[2..n-1]="non-"|0<1=[] yn=h[]n++c n++"prime" main=readLn>>=putStr.y 
+5
Aug 23 '10 at 3:30
source share

Javascript 244 250

 function h(n){p=n=n<2?10:n;a=",";w="";s=[];while((y=a+s.join(a)+a).indexOf(a+n+a)<0){s.push(n);k=""+n;n=0;for(i=0;i<k.length;)c=k.charAt(i++),n+=c*c}w+=y.indexOf(",1,")<0?"sad ":"happy ";for(i=2;i<p;)p=p%i++?p:0;w+=p?"":"non-";return w+"prime"} 

The above code should work in browsers without additional fancy functions and functions (for example, Array.prototype.indexOf and [] for strings), but I have not tested it outside of Firefox.

Remember that all but n are global variables (I'm just cheap).

Using

 h(139) // returns "happy prime" 
+5
Aug 23 '10 at 4:52
source share

Python 2.6

happy.py: 280,314,333 characters, 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):] 

Using:

 $ 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.argv[1]) print "%s %sprime" % (('sad','happy')[is_happy(n)], ('non-','')[is_prime(n)]) 
+4
Aug 23 '10 at 0:13
source share

Java: 294,286,285,282,277,262,260 characters




  • Update 1 : replaced BigInteger#isProbablePrime() regex . 8 characters saved.

  • Update 2 : replace && with & (oops). 1 char saved.

  • Update 3 : reorganized s bit. 3 characters saved.

  • Update 4 : the test for n!=1 was redundant. 5 characters saved.

  • Update 5 : Replaced regex for loop and reorganized happy for small loops. 15 characters saved.

  • Update 6 : replace int/Integer with long/Long . 2 characters saved.




 import java.util.*;class H{public static void main(String[]a){long n=new Long(a[0]),p=n>1?1:0,s,d=1;while(++d<n)if(n%d<1)p=0;for(Set c=new HashSet();c.add(n);n=s)for(s=0;n>0;s+=d*d,n/=10)d=n%10;System.out.printf("%s %sprime",n>1?"sad":"happy",p>0?"":"non-");}} 



With newline characters:

 import java.util.*; class H{ public static void main(String[]a){ long n=new Long(a[0]),p=n>1?1:0,s,d=1; while(++d<n)if(n%d<1)p=0; for(Set c=new HashSet();c.add(n);n=s)for(s=0;n>0;s+=d*d,n/=10)d=n%10; System.out.printf("%s %sprime",n>1?"sad":"happy",p>0?"":"non-"); } } 
+4
Aug 23 2018-10-18T00:
source share

J: 113 characters

 h=.1=$:@([:+/[:*:@"."0":)`]@.(e.&1 4) 1!:2&2;(({&('sad ';'happy '))@h,({&('non-prime';'prime'))@(1&p:))".(1!:1]3) 

 $ 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 
+4
Aug 23 2018-10-23T00:
source share

Perl, 135C

 sub h{my$s;$s+=$_**2for split//,pop;($s-4)?($s-1)?&h($s):1:0}$a=pop; print h($a)?happy:sad,$",(1x$a)=~/^1?$|^(11+?)\1+$/&&"non-",prime 

Combined C and Perl

+3
Aug 23 '10 at 2:01
source share

C ++, 258,231,230,227 characters

 #include<iostream> #define w while int m,n,i,j,t=10;int main(){w(std::cin>>n){j=0,m=n;w(n>1){i=0;do i+=n%t*(n%t);w(n/=t);n=n*n+i;n=++j&0xFFFF?n:0;}i=1;w(m%++i&&j>1);std::cout<<(n?"happy":"sad")<<(im?" non-":" ")<<"prime\n";}} 

not the best language for playing golf, anyway gave him a good chance. Most of this is direct C, so it’s likely to be shorter also on C. In addition,

EDIT

In general, I came up with this, think that he is almost at the limit now without a complete rewrite.

I also forgot to add that this assumes that there are no numbers with a sequence with more than 0xFFFF digits, which is a pretty reasonable assumption.

EDIT 2

bug fixed. rebuilt to remove excessive calls in std :: cout.

+3
Aug 23 '10 at 6:01
source share

VBA 245 characters

A good starter, cut off if time permits. Its my only second go to the code golf club!

 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 < N O = O & " Prime" Debug.Print O End Sub 
+3
Aug 23 2018-10-23T00:
source share

MATLAB - 166 characters

 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] 

Using

 happyprime 139 ans = Happy prime 
+3
Aug 23 '10 at 17:35
source share

Clojure, 353,318,298,261,230 characters

 (defn h[xm](cond(= x 1)"happy "(mx)"sad ":else(recur(reduce +(for[n(map #(-(int %)48)(str x))](* nn)))(assoc mx 1))))(println(let [x (read)](str(hx{})(if(re-matches #"^1$|^(11+)?\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 rely on the clojure contrib tab for a sequence of primes. I wonder if using loops for loops will be shorter than recursion?

I read regular expression prime checks. This is awesome and removes 30 characters and my dependence on clojure.contrib. I also reorganized the command line, parsing which and built in the function.

Pre-golf (somewhat outdated):

 (defn h[xm] (cond (= x 1) "happy " (mx) "sad " :else (recur (reduce + (for [n (map #(- (int %) 48) (str x))] (* nn))) (assoc mx 1)))) (println (let [x (read)] (str (hx{}) (if (re-matches #"^1$|^(11+)?\1+"(apply str(repeat x \1))) "non-" "") "prime"))) 
+2
Aug 23 '10 at 1:56
source share

F #, 249 characters

 let n=stdin.ReadLine()|>int let rec sx=seq{yield x;yield!string x|>Seq.sumBy(fun c->(int c-48)*(int c-48))|>s} printfn"%s %sprime"(if sn|>Seq.take 99|>Seq.exists((=)1)then"happy"else"sad")(if[2..n/2]|>Seq.exists(fun d->n%d=0)then"non-"else"") 
+2
Aug 23 2018-10-10T00:
source share

Scala, 253,247,246

 object H{def main(a:Array[String]){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<2)"happy"else if(s(k))"sad"else{s+=k;r(k)}} printf("%s %sprime",r(n),if(n<2|(2 to n-1 exists(n%_==0)))"non-"else"")}} 

Perhaps there are some improvements. Damned test for 1 as a misuse of 6 characters: - (

+2
Aug 23 '10 at 7:37
source share

PHP 217 Templates

 $t=$argv[1];for($z=$t-1,$p=1;$z&&++$p<$t;)$z=$t%$p;$f=array(1);while(!in_array($t,$f,1)){$f[]=$t;$t=array_reduce(str_split($t),function($v,$c){return $v+=$c*$c;});}print($t<2?"happy ":"sad ").(!$z?"non-":"")."prime"; 

Using:

 $ php -r '$t=$argv[1];for($z=$t-1,$p=1;$z&&++$p<$t;)$z=$t%$p;$f=array(1);while(!in_array($t,$f,1)){$f[]=$t;$t=array_reduce(str_split($t),function($v,$c){return $v+=$c*$c;});}print($t<2?"happy ":"sad ").(!$z?"non-":"")."prime";' 139 happy prime 
+2
Aug 24 '10 at 0:25
source share

Javascript, 192 190 185 182 165 158 characters

Initial verification is performed from 2 to the square root of N I lost a few characters there ...

In one line:

 for(x=2,y=m=n=prompt();x*x<y&&n%x++;);for(s={};!s[m];m=p)for(s[m]=1,p=0;m;m=(m-=k=m%10)/10,p+=k*k);alert((m-1?'sad':'happy')+(n-1&&x*x>y?' ':' 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*x<y && n%x++;) // Checking for happiness // the loop is broken out of if m is already encountered // the m==1 after the loop indicates happy number for(s={}; !s[m]; m=p) for (s[m]=1, p=0; m; m=(m -= k=m%10)/10, p+=k * k); alert((m-1 ? 'sad' : 'happy') + (n-1 && x*x>y ? ' ' : ' non-') + 'prime') 

Check out: http://jsfiddle.net/TwxAW/6/

+2
Aug 24 '10 at 12:02
source share

Perl, 113 109 105 characters

Beating all Python answers for now! 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 
+2
Aug 24 '10 at 19:11
source share

Python 2.6, 300 298 294 characters

Unlike the previous answer, this does not use regex.

I'm sure there is a way to shorten my h(x) function, but I'm still learning Python, so I have no idea.

p(x) returns True if it is not simple. h(x) returns true if it is happy. I did t = True to reduce the number of characters when checking the truth.

 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' 
+1
Aug 23 '10 at 1:36
source share

Python ( 285 270 269 246 241 247 240 237 characters 21 twenty 21 eighteen 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 has increased, an error has appeared: -P

+1
Aug 23 2018-10-10T00:
source share

Python, 169 168 158 157 166 164 162 characters, 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))<2]+"prime" 

It takes a number from stdin and does not flush with regular expressions, like other python answers, although I have to admit it's pretty cool. I could also shave 6 characters using backticks instead of the str function, but letting me play well.

EDIT: Fixed a bug with 1 state of a prime number that increased the number of characters by 10. I believe there should be a more concise way for this than mine.

EDIT 2: Obviously, python 2.6 allows print[1, 2] without a space between them.

EDIT 3: Used a different calculation for lucky numbers

+1
Aug 23 2018-10-18T00:
source share

Python - 142 characters

I played with this idea, but it turned out too long. Perhaps someone can find a way to make it shorter. Maybe in Ruby it will be better. It should be interesting to understand how this works :)

 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<1]==[1]):]%['sad','happy'][1in L] 
+1
Aug 25 '10 at 1:30
source share

GNU sed, 146,125 characters

Run the sed -rf file. Using -r saves 5 backslashes.

Requires bc , printf and a shell that supports here-strings.

 h s/^/printf %*s /e s/^ $|^( +)\1+$/non-/ s/ *$/prime/ x :a s/./+&*&/g s//bc<<</e tb :b s/^1$/happy/ s/^4$/sad/ Ta G s/\n/ / 

GNU sed, 155,141 characters (no printf required, no line here)

Uses << static> << static> << → yes and head instead of printf

<.
 h :a s/./+&*&/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 characters (slightly poorly formatted output)

The version is slightly shorter, does not take into account the formatting of the output (it has additional spaces and a new line between happy / sad and (non) prime).

 h :a s/./+&*&/g s//bc<<</e tb :b s/^1$/happy/ s/^4$/sad/ Ta p g s/^/printf %*s /e s/^ $|^( +)\1+$/non-/ s/$/prime/ 
+1
Aug 25 '10 at 17:40
source share
  • one
  • 2



All Articles