A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
8
Task/Happy-numbers/0DESCRIPTION
Normal file
8
Task/Happy-numbers/0DESCRIPTION
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
From Wikipedia, the free encyclopedia:
|
||||
:A [[wp:Happy number|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. Display an example of your output here.
|
||||
|
||||
'''Task:''' Find and print the first 8 happy numbers.
|
||||
|
||||
See also:
|
||||
* [[oeis:A007770|The happy numbers on OEIS: A007770]]
|
||||
* [[oeis:A031177|The unhappy numbers on OEIS; A031177]]
|
||||
2
Task/Happy-numbers/1META.yaml
Normal file
2
Task/Happy-numbers/1META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
note: Arithmetic operations
|
||||
25
Task/Happy-numbers/ACL2/happy-numbers.acl2
Normal file
25
Task/Happy-numbers/ACL2/happy-numbers.acl2
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
(include-book "arithmetic-3/top" :dir :system)
|
||||
|
||||
(defun sum-of-digit-squares (n)
|
||||
(if (zp n)
|
||||
0
|
||||
(+ (expt (mod n 10) 2)
|
||||
(sum-of-digit-squares (floor n 10)))))
|
||||
|
||||
(defun is-happy-r (n seen)
|
||||
(let ((next (sum-of-digit-squares n)))
|
||||
(cond ((= next 1) t)
|
||||
((member next seen) nil)
|
||||
(t (is-happy-r next (cons next seen))))))
|
||||
|
||||
(defun is-happy (n)
|
||||
(is-happy-r n nil))
|
||||
|
||||
(defun first-happy-nums-r (n i)
|
||||
(cond ((zp n) nil)
|
||||
((is-happy i)
|
||||
(cons i (first-happy-nums-r (1- n) (1+ i))))
|
||||
(t (first-happy-nums-r n (1+ i)))))
|
||||
|
||||
(defun first-happy-nums (n)
|
||||
(first-happy-nums-r n 1))
|
||||
25
Task/Happy-numbers/ALGOL-68/happy-numbers.alg
Normal file
25
Task/Happy-numbers/ALGOL-68/happy-numbers.alg
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
INT base10 = 10, num happy = 8;
|
||||
|
||||
PROC next = (INT in n)INT: (
|
||||
INT n := in n;
|
||||
INT out := 0;
|
||||
WHILE n NE 0 DO
|
||||
out +:= ( n MOD base10 ) ** 2;
|
||||
n := n OVER base10
|
||||
OD;
|
||||
out
|
||||
);
|
||||
|
||||
PROC is happy = (INT in n)BOOL: (
|
||||
INT n := in n;
|
||||
FOR i WHILE n NE 1 AND n NE 4 DO n := next(n) OD;
|
||||
n=1
|
||||
);
|
||||
|
||||
INT count := 0;
|
||||
FOR i WHILE count NE num happy DO
|
||||
IF is happy(i) THEN
|
||||
count +:= 1;
|
||||
print((i, new line))
|
||||
FI
|
||||
OD
|
||||
20
Task/Happy-numbers/APL/happy-numbers.apl
Normal file
20
Task/Happy-numbers/APL/happy-numbers.apl
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
∇ HappyNumbers arg;⎕IO;∆roof;∆first;bin;iroof
|
||||
[1] ⍝0: Happy number
|
||||
[2] ⍝1: http://rosettacode.org/wiki/Happy_numbers
|
||||
[3] ⎕IO←1 ⍝ Index origin
|
||||
[4] ∆roof ∆first←2↑arg,10 ⍝
|
||||
[5]
|
||||
[6] bin←{
|
||||
[7] ⍺←⍬ ⍝ Default left arg
|
||||
[8] ⍵=1:1 ⍝ Always happy!
|
||||
[9]
|
||||
[10] numbers←⍎¨1⊂⍕⍵ ⍝ Split numbers into parts
|
||||
[11] next←+/{⍵*2}¨numbers ⍝ Sum and square of numbers
|
||||
[12]
|
||||
[13] next∊⍺:0 ⍝ Return 0, if already exists
|
||||
[14] (⍺,next)∇ next ⍝ Check next number (recursive)
|
||||
[15]
|
||||
[16] }¨iroof←⍳∆roof ⍝ Does all numbers upto ∆root smiles?
|
||||
[17]
|
||||
[18] ⎕←~∘0¨∆first↑bin/iroof ⍝ Show ∆first numbers, but not 0
|
||||
∇
|
||||
41
Task/Happy-numbers/AWK/happy-numbers-1.awk
Normal file
41
Task/Happy-numbers/AWK/happy-numbers-1.awk
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
function is_happy(n)
|
||||
{
|
||||
if ( n in happy ) return 1;
|
||||
if ( n in unhappy ) return 0;
|
||||
cycle[""] = 0
|
||||
while( (n!=1) && !(n in cycle) ) {
|
||||
cycle[n] = n
|
||||
new_n = 0
|
||||
while(n>0) {
|
||||
d = n % 10
|
||||
new_n += d*d
|
||||
n = int(n/10)
|
||||
}
|
||||
n = new_n
|
||||
}
|
||||
if ( n == 1 ) {
|
||||
for (i_ in cycle) {
|
||||
happy[cycle[i_]] = 1
|
||||
delete cycle[i_]
|
||||
}
|
||||
return 1
|
||||
} else {
|
||||
for (i_ in cycle) {
|
||||
unhappy[cycle[i_]] = 1
|
||||
delete cycle[i_]
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
BEGIN {
|
||||
cnt = 0
|
||||
happy[""] = 0
|
||||
unhappy[""] = 0
|
||||
for(j=1; (cnt < 8); j++) {
|
||||
if ( is_happy(j) == 1 ) {
|
||||
cnt++
|
||||
print j
|
||||
}
|
||||
}
|
||||
}
|
||||
28
Task/Happy-numbers/AWK/happy-numbers-2.awk
Normal file
28
Task/Happy-numbers/AWK/happy-numbers-2.awk
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
BEGIN {
|
||||
for (i = 1; i < 50; ++i){
|
||||
if (isHappy(i)) {
|
||||
print i;
|
||||
}
|
||||
}
|
||||
exit
|
||||
}
|
||||
|
||||
function isHappy(n, seen) {
|
||||
delete seen;
|
||||
while (1) {
|
||||
n = sumSqrDig(n)
|
||||
if (seen[n]) {
|
||||
return n == 1
|
||||
}
|
||||
seen[n] = 1
|
||||
}
|
||||
}
|
||||
|
||||
function sumSqrDig(n, d, tot) {
|
||||
while (n) {
|
||||
d = n % 10
|
||||
tot += d * d
|
||||
n = int(n/10)
|
||||
}
|
||||
return tot
|
||||
}
|
||||
42
Task/Happy-numbers/ActionScript/happy-numbers.as
Normal file
42
Task/Happy-numbers/ActionScript/happy-numbers.as
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
function sumOfSquares(n:uint)
|
||||
{
|
||||
var sum:uint = 0;
|
||||
while(n != 0)
|
||||
{
|
||||
sum += (n%10)*(n%10);
|
||||
n /= 10;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
function isInArray(n:uint, array:Array)
|
||||
{
|
||||
for(var k = 0; k < array.length; k++)
|
||||
if(n == array[k]) return true;
|
||||
return false;
|
||||
}
|
||||
function isHappy(n)
|
||||
{
|
||||
var sequence:Array = new Array();
|
||||
while(n != 1)
|
||||
{
|
||||
sequence.push(n);
|
||||
n = sumOfSquares(n);
|
||||
if(isInArray(n,sequence))return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function printHappy()
|
||||
{
|
||||
var numbersLeft:uint = 8;
|
||||
var numberToTest:uint = 1;
|
||||
while(numbersLeft != 0)
|
||||
{
|
||||
if(isHappy(numberToTest))
|
||||
{
|
||||
trace(numberToTest);
|
||||
numbersLeft--;
|
||||
}
|
||||
numberToTest++;
|
||||
}
|
||||
}
|
||||
printHappy();
|
||||
41
Task/Happy-numbers/Ada/happy-numbers.ada
Normal file
41
Task/Happy-numbers/Ada/happy-numbers.ada
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
with Ada.Containers.Ordered_Sets;
|
||||
|
||||
procedure Test_Happy_Digits is
|
||||
function Is_Happy (N : Positive) return Boolean is
|
||||
package Sets_Of_Positive is new Ada.Containers.Ordered_Sets (Positive);
|
||||
use Sets_Of_Positive;
|
||||
function Next (N : Positive) return Natural is
|
||||
Sum : Natural := 0;
|
||||
Accum : Natural := N;
|
||||
begin
|
||||
while Accum > 0 loop
|
||||
Sum := Sum + (Accum mod 10) ** 2;
|
||||
Accum := Accum / 10;
|
||||
end loop;
|
||||
return Sum;
|
||||
end Next;
|
||||
Current : Positive := N;
|
||||
Visited : Set;
|
||||
begin
|
||||
loop
|
||||
if Current = 1 then
|
||||
return True;
|
||||
elsif Visited.Contains (Current) then
|
||||
return False;
|
||||
else
|
||||
Visited.Insert (Current);
|
||||
Current := Next (Current);
|
||||
end if;
|
||||
end loop;
|
||||
end Is_Happy;
|
||||
Found : Natural := 0;
|
||||
begin
|
||||
for N in Positive'Range loop
|
||||
if Is_Happy (N) then
|
||||
Put (Integer'Image (N));
|
||||
Found := Found + 1;
|
||||
exit when Found = 8;
|
||||
end if;
|
||||
end loop;
|
||||
end Test_Happy_Digits;
|
||||
21
Task/Happy-numbers/AutoHotkey/happy-numbers.ahk
Normal file
21
Task/Happy-numbers/AutoHotkey/happy-numbers.ahk
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
Loop {
|
||||
If isHappy(A_Index) {
|
||||
out .= (out="" ? "" : ",") . A_Index
|
||||
i ++
|
||||
If (i = 8) {
|
||||
MsgBox, The first 8 happy numbers are: %out%
|
||||
ExitApp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
isHappy(num, list="") {
|
||||
list .= (list="" ? "" : ",") . num
|
||||
Loop, Parse, num
|
||||
sum += A_LoopField ** 2
|
||||
If (sum = 1)
|
||||
Return true
|
||||
Else If sum in %list%
|
||||
Return false
|
||||
Else Return isHappy(sum, list)
|
||||
}
|
||||
22
Task/Happy-numbers/AutoIt/happy-numbers-1.autoit
Normal file
22
Task/Happy-numbers/AutoIt/happy-numbers-1.autoit
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
$c = 0
|
||||
$k = 0
|
||||
While $c < 8
|
||||
$k += 1
|
||||
$n = $k
|
||||
While $n <> 1
|
||||
$s = StringSplit($n, "")
|
||||
$t = 0
|
||||
For $i = 1 To $s[0]
|
||||
$t += $s[$i] ^ 2
|
||||
Next
|
||||
$n = $t
|
||||
Switch $n
|
||||
Case 4,16,37,58,89,145,42,20
|
||||
ExitLoop
|
||||
EndSwitch
|
||||
WEnd
|
||||
If $n = 1 Then
|
||||
ConsoleWrite($k & " is Happy" & @CRLF)
|
||||
$c += 1
|
||||
EndIf
|
||||
WEnd
|
||||
24
Task/Happy-numbers/AutoIt/happy-numbers-2.autoit
Normal file
24
Task/Happy-numbers/AutoIt/happy-numbers-2.autoit
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
$c = 0
|
||||
$k = 0
|
||||
While $c < 8
|
||||
$a = ObjCreate("System.Collections.ArrayList")
|
||||
$k += 1
|
||||
$n = $k
|
||||
While $n <> 1
|
||||
If $a.Contains($n) Then
|
||||
ExitLoop
|
||||
EndIf
|
||||
$a.add($n)
|
||||
$s = StringSplit($n, "")
|
||||
$t = 0
|
||||
For $i = 1 To $s[0]
|
||||
$t += $s[$i] ^ 2
|
||||
Next
|
||||
$n = $t
|
||||
WEnd
|
||||
If $n = 1 Then
|
||||
ConsoleWrite($k & " is Happy" & @CRLF)
|
||||
$c += 1
|
||||
EndIf
|
||||
$a.Clear
|
||||
WEnd
|
||||
21
Task/Happy-numbers/BBC-BASIC/happy-numbers.bbc
Normal file
21
Task/Happy-numbers/BBC-BASIC/happy-numbers.bbc
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
number% = 0
|
||||
total% = 0
|
||||
REPEAT
|
||||
number% += 1
|
||||
IF FNhappy(number%) THEN
|
||||
PRINT number% " is a happy number"
|
||||
total% += 1
|
||||
ENDIF
|
||||
UNTIL total% = 8
|
||||
END
|
||||
|
||||
DEF FNhappy(num%)
|
||||
LOCAL digit&()
|
||||
DIM digit&(10)
|
||||
REPEAT
|
||||
digit&() = 0
|
||||
$$^digit&(0) = STR$(num%)
|
||||
digit&() AND= 15
|
||||
num% = MOD(digit&())^2 + 0.5
|
||||
UNTIL num% = 1 OR num% = 4
|
||||
= (num% = 1)
|
||||
81
Task/Happy-numbers/Batch-File/happy-numbers.bat
Normal file
81
Task/Happy-numbers/Batch-File/happy-numbers.bat
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
@echo off
|
||||
setlocal enableDelayedExpansion
|
||||
::Define a list with 10 terms as a convenience for defining a loop
|
||||
set "L10=0 1 2 3 4 5 6 7 8 9"
|
||||
shift /1 & goto %1
|
||||
exit /b
|
||||
|
||||
|
||||
:list min count
|
||||
:: This routine prints all happy numbers > min (arg1)
|
||||
:: until it finds count (arg2) happy numbers.
|
||||
set /a "n=%~1, cnt=%~2"
|
||||
call :listInternal
|
||||
exit /b
|
||||
|
||||
|
||||
:test min [max]
|
||||
:: This routine sequentially tests numbers between min (arg1) and max (arg2)
|
||||
:: to see if they are happy. If max is not specified then it defaults to min.
|
||||
set /a "min=%~1"
|
||||
if "%~2" neq "" (set /a "max=%~2") else set max=%min%
|
||||
::The FOR /L loop does not detect integer overflow, so must protect against
|
||||
::an infinite loop when max=0x7FFFFFFFF
|
||||
set end=%max%
|
||||
if %end% equ 2147483647 set /a end-=1
|
||||
for /l %%N in (%min% 1 %end%) do (
|
||||
call :testInternal %%N && (echo %%N is happy :^)) || echo %%N is sad :(
|
||||
)
|
||||
if %end% neq %max% call :testInternal %max% && (echo %max% is happy :^)) || echo %max% is sad :(
|
||||
exit /b
|
||||
|
||||
|
||||
:listInternal
|
||||
:: This loop sequentially tests each number >= n. The loop conditionally
|
||||
:: breaks within the body once cnt happy numbers have been found, or if
|
||||
:: the max integer value is reached. Performance is improved by using a
|
||||
:: FOR loop to perform most of the looping, with a GOTO only needed once
|
||||
:: per 100 iterations.
|
||||
for %%. in (
|
||||
%L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10%
|
||||
) do (
|
||||
call :testInternal !n! && (
|
||||
echo !n!
|
||||
set /a cnt-=1
|
||||
if !cnt! leq 0 exit /b 0
|
||||
)
|
||||
if !n! equ 2147483647 (
|
||||
>&2 echo ERROR: Maximum integer value reached
|
||||
exit /b 1
|
||||
)
|
||||
set /a n+=1
|
||||
)
|
||||
goto :listInternal
|
||||
|
||||
|
||||
:testInternal n
|
||||
:: This routine loops until the sum of squared digits converges on 1 (happy)
|
||||
:: or it detects a cycle (sad). It exits with errorlevel 0 for happy and 1 for sad.
|
||||
:: Performance is improved by using a FOR loop for the looping instead of a GOTO.
|
||||
:: Numbers less than 1000 never neeed more than 20 iterations, and any number
|
||||
:: with 4 or more digits shrinks by at least one digit each iteration.
|
||||
:: Since Windows batch can't handle more than 10 digits, allowance for 27
|
||||
:: iterations is enough, and 30 is more than adequate.
|
||||
setlocal
|
||||
set n=%1
|
||||
for %%. in (%L10% %L10% %L10%) do (
|
||||
if !n!==1 exit /b 0
|
||||
%= Only numbers < 1000 can cycle =%
|
||||
if !n! lss 1000 (
|
||||
if defined t.!n! exit /b 1
|
||||
set t.!n!=1
|
||||
)
|
||||
%= Sum the squared digits =%
|
||||
%= Batch can't handle numbers greater than 10 digits so we can use =%
|
||||
%= a constrained FOR loop and avoid a slow goto =%
|
||||
set sum=0
|
||||
for /l %%N in (1 1 10) do (
|
||||
if !n! gtr 0 set /a "sum+=(n%%10)*(n%%10), n/=10"
|
||||
)
|
||||
set /a n=sum
|
||||
)
|
||||
36
Task/Happy-numbers/Bori/happy-numbers.bori
Normal file
36
Task/Happy-numbers/Bori/happy-numbers.bori
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
bool isHappy (int n)
|
||||
{
|
||||
ints cache;
|
||||
|
||||
while (n != 1)
|
||||
{
|
||||
int sum = 0;
|
||||
|
||||
if (cache.contains(n))
|
||||
return false;
|
||||
|
||||
cache.add(n);
|
||||
while (n != 0)
|
||||
{
|
||||
int digit = n % 10;
|
||||
sum += (digit * digit);
|
||||
n = (int)(n / 10);
|
||||
}
|
||||
n = sum;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void test ()
|
||||
{
|
||||
int num = 1;
|
||||
ints happynums;
|
||||
|
||||
while (happynums.count() < 8)
|
||||
{
|
||||
if (isHappy(num))
|
||||
happynums.add(num);
|
||||
num++;
|
||||
}
|
||||
puts("First 8 happy numbers : " + str.newline + happynums);
|
||||
}
|
||||
29
Task/Happy-numbers/Brat/happy-numbers.brat
Normal file
29
Task/Happy-numbers/Brat/happy-numbers.brat
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
include :set
|
||||
|
||||
happiness = set.new 1
|
||||
sadness = set.new
|
||||
|
||||
sum_of_squares_of_digits = { num |
|
||||
num.to_s.dice.reduce 0 { sum, n | sum = sum + n.to_i ^ 2 }
|
||||
}
|
||||
|
||||
happy? = { n, seen = set.new |
|
||||
when {true? happiness.include? n } { happiness.merge seen << n; true }
|
||||
{ true? sadness.include? n } { sadness.merge seen; false }
|
||||
{ true? seen.include? n } { sadness.merge seen; false }
|
||||
{ true } { seen << n; happy? sum_of_squares_of_digits(n), seen }
|
||||
}
|
||||
|
||||
num = 1
|
||||
happies = []
|
||||
|
||||
while { happies.length < 8 } {
|
||||
true? happy?(num)
|
||||
{ happies << num }
|
||||
|
||||
num = num + 1
|
||||
}
|
||||
|
||||
p "First eight happy numbers: #{happies}"
|
||||
p "Happy numbers found: #{happiness.to_array.sort}"
|
||||
p "Sad numbers found: #{sadness.to_array.sort}"
|
||||
36
Task/Happy-numbers/C++/happy-numbers-1.cpp
Normal file
36
Task/Happy-numbers/C++/happy-numbers-1.cpp
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
#include <map>
|
||||
#include <set>
|
||||
|
||||
bool happy(int number) {
|
||||
static std::map<int, bool> cache;
|
||||
|
||||
std::set<int> cycle;
|
||||
while (number != 1 && !cycle.count(number)) {
|
||||
if (cache.count(number)) {
|
||||
number = cache[number] ? 1 : 0;
|
||||
break;
|
||||
}
|
||||
cycle.insert(number);
|
||||
int newnumber = 0;
|
||||
while (number > 0) {
|
||||
int digit = number % 10;
|
||||
newnumber += digit * digit;
|
||||
number /= 10;
|
||||
}
|
||||
number = newnumber;
|
||||
}
|
||||
bool happiness = number == 1;
|
||||
for (std::set<int>::const_iterator it = cycle.begin();
|
||||
it != cycle.end(); it++)
|
||||
cache[*it] = happiness;
|
||||
return happiness;
|
||||
}
|
||||
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
for (int i = 1; i < 50; i++)
|
||||
if (happy(i))
|
||||
std::cout << i << std::endl;
|
||||
return 0;
|
||||
}
|
||||
41
Task/Happy-numbers/C++/happy-numbers-2.cpp
Normal file
41
Task/Happy-numbers/C++/happy-numbers-2.cpp
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
unsigned int happy_iteration(unsigned int n)
|
||||
{
|
||||
unsigned int result = 0;
|
||||
while (n > 0)
|
||||
{
|
||||
unsigned int lastdig = n % 10;
|
||||
result += lastdig*lastdig;
|
||||
n /= 10;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool is_happy(unsigned int n)
|
||||
{
|
||||
unsigned int n2 = happy_iteration(n);
|
||||
while (n != n2)
|
||||
{
|
||||
n = happy_iteration(n);
|
||||
n2 = happy_iteration(happy_iteration(n2));
|
||||
}
|
||||
return n == 1;
|
||||
}
|
||||
|
||||
#include <iostream>
|
||||
|
||||
int main()
|
||||
{
|
||||
unsigned int current_number = 1;
|
||||
|
||||
unsigned int happy_count = 0;
|
||||
while (happy_count != 8)
|
||||
{
|
||||
if (is_happy(current_number))
|
||||
{
|
||||
std::cout << current_number << " ";
|
||||
++happy_count;
|
||||
}
|
||||
++current_number;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
33
Task/Happy-numbers/C/happy-numbers-1.c
Normal file
33
Task/Happy-numbers/C/happy-numbers-1.c
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
#include <stdio.h>
|
||||
|
||||
#define CACHE 256
|
||||
enum { h_unknown = 0, h_yes, h_no };
|
||||
unsigned char buf[CACHE] = {0, h_yes, 0};
|
||||
|
||||
int happy(int n)
|
||||
{
|
||||
int sum = 0, x, nn;
|
||||
if (n < CACHE) {
|
||||
if (buf[n]) return 2 - buf[n];
|
||||
buf[n] = h_no;
|
||||
}
|
||||
|
||||
for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;
|
||||
|
||||
x = happy(sum);
|
||||
if (n < CACHE) buf[n] = 2 - x;
|
||||
return x;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int i, cnt = 8;
|
||||
for (i = 1; cnt || !printf("\n"); i++)
|
||||
if (happy(i)) --cnt, printf("%d ", i);
|
||||
|
||||
printf("The %dth happy number: ", cnt = 1000000);
|
||||
for (i = 1; cnt; i++)
|
||||
if (happy(i)) --cnt || printf("%d\n", i);
|
||||
|
||||
return 0;
|
||||
}
|
||||
31
Task/Happy-numbers/C/happy-numbers-2.c
Normal file
31
Task/Happy-numbers/C/happy-numbers-2.c
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
#include <stdio.h>
|
||||
|
||||
int dsum(int n)
|
||||
{
|
||||
int sum, x;
|
||||
for (sum = 0; n; n /= 10) x = n % 10, sum += x * x;
|
||||
return sum;
|
||||
}
|
||||
|
||||
int happy(int n)
|
||||
{
|
||||
int nn;
|
||||
while (n > 999) n = dsum(n); /* 4 digit numbers can't cycle */
|
||||
nn = dsum(n);
|
||||
while (nn != n && nn != 1)
|
||||
n = dsum(n), nn = dsum(dsum(nn));
|
||||
return n == 1;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int i, cnt = 8;
|
||||
for (i = 1; cnt || !printf("\n"); i++)
|
||||
if (happy(i)) --cnt, printf("%d ", i);
|
||||
|
||||
printf("The %dth happy number: ", cnt = 1000000);
|
||||
for (i = 1; cnt; i++)
|
||||
if (happy(i)) --cnt || printf("%d\n", i);
|
||||
|
||||
return 0;
|
||||
}
|
||||
14
Task/Happy-numbers/Clojure/happy-numbers.clj
Normal file
14
Task/Happy-numbers/Clojure/happy-numbers.clj
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
(defn- digit-to-num [d] (Character/digit d 10))
|
||||
(defn- square [n] (* n n))
|
||||
|
||||
(defn happy? [n]
|
||||
(loop [n n, seen #{}]
|
||||
(cond (= n 1) true
|
||||
(seen n) false
|
||||
:else
|
||||
(recur (reduce + (map (comp square digit-to-num) (str n)))
|
||||
(conj seen n)))))
|
||||
|
||||
(def happy-numbers (filter happy? (iterate inc 1)))
|
||||
|
||||
(println (take 8 happy-numbers))
|
||||
22
Task/Happy-numbers/CoffeeScript/happy-numbers.coffee
Normal file
22
Task/Happy-numbers/CoffeeScript/happy-numbers.coffee
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
happy = (n) ->
|
||||
seen = {}
|
||||
while true
|
||||
n = sum_digit_squares(n)
|
||||
return true if n == 1
|
||||
return false if seen[n]
|
||||
seen[n] = true
|
||||
|
||||
sum_digit_squares = (n) ->
|
||||
sum = 0
|
||||
for c in n.toString()
|
||||
d = parseInt(c)
|
||||
sum += d*d
|
||||
sum
|
||||
|
||||
i = 1
|
||||
cnt = 0
|
||||
while cnt < 8
|
||||
if happy(i)
|
||||
console.log i
|
||||
cnt += 1
|
||||
i += 1
|
||||
21
Task/Happy-numbers/Common-Lisp/happy-numbers.lisp
Normal file
21
Task/Happy-numbers/Common-Lisp/happy-numbers.lisp
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
(defun sqr (n)
|
||||
(* n n))
|
||||
|
||||
(defun sum-of-sqr-dgts (n)
|
||||
(loop for i = n then (floor i 10)
|
||||
while (plusp i)
|
||||
sum (sqr (mod i 10))))
|
||||
|
||||
(defun happy-p (n &optional cache)
|
||||
(or (= n 1)
|
||||
(unless (find n cache)
|
||||
(happy-p (sum-of-sqr-dgts n)
|
||||
(cons n cache)))))
|
||||
|
||||
(defun happys (&aux (happys 0))
|
||||
(loop for i from 1
|
||||
while (< happys 8)
|
||||
when (happy-p i)
|
||||
collect i and do (incf happys)))
|
||||
|
||||
(print (happys))
|
||||
23
Task/Happy-numbers/D/happy-numbers-1.d
Normal file
23
Task/Happy-numbers/D/happy-numbers-1.d
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import std.stdio, std.algorithm, std.range;
|
||||
|
||||
bool isHappy(int n) pure nothrow {
|
||||
int[int] past;
|
||||
|
||||
while (true) {
|
||||
int total = 0;
|
||||
while (n > 0) {
|
||||
total += (n % 10) ^^ 2;
|
||||
n /= 10;
|
||||
}
|
||||
if (total == 1)
|
||||
return true;
|
||||
if (total in past)
|
||||
return false;
|
||||
n = total;
|
||||
past[total] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
int.max.iota().filter!isHappy().take(8).writeln();
|
||||
}
|
||||
19
Task/Happy-numbers/D/happy-numbers-2.d
Normal file
19
Task/Happy-numbers/D/happy-numbers-2.d
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import std.stdio, std.algorithm, std.range, std.conv;
|
||||
|
||||
bool isHappy(int n) /*pure nothrow*/ {
|
||||
int[int] seen;
|
||||
|
||||
while (true) {
|
||||
const t = n.text().map!q{(a - '0') ^^ 2}().reduce!q{a + b}();
|
||||
if (t == 1)
|
||||
return true;
|
||||
if (t in seen)
|
||||
return false;
|
||||
n = t;
|
||||
seen[t] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
int.max.iota().filter!isHappy().take(8).writeln();
|
||||
}
|
||||
30
Task/Happy-numbers/DWScript/happy-numbers.dwscript
Normal file
30
Task/Happy-numbers/DWScript/happy-numbers.dwscript
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
function IsHappy(n : Integer) : Boolean;
|
||||
var
|
||||
cache : array of Integer;
|
||||
sum : Integer;
|
||||
begin
|
||||
while True do begin
|
||||
sum := 0;
|
||||
while n>0 do begin
|
||||
sum += Sqr(n mod 10);
|
||||
n := n div 10;
|
||||
end;
|
||||
if sum = 1 then
|
||||
Exit(True);
|
||||
if sum in cache then
|
||||
Exit(False);
|
||||
n := sum;
|
||||
cache.Add(sum);
|
||||
end;
|
||||
end;
|
||||
|
||||
var n := 8;
|
||||
var i : Integer;
|
||||
|
||||
while n>0 do begin
|
||||
Inc(i);
|
||||
if IsHappy(i) then begin
|
||||
PrintLn(i);
|
||||
Dec(n);
|
||||
end;
|
||||
end;
|
||||
35
Task/Happy-numbers/Dart/happy-numbers.dart
Normal file
35
Task/Happy-numbers/Dart/happy-numbers.dart
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
main() {
|
||||
HashMap<int,bool> happy=new HashMap<int,bool>();
|
||||
happy[1]=true;
|
||||
|
||||
int count=0;
|
||||
int i=0;
|
||||
|
||||
while(count<8) {
|
||||
if(happy[i]==null) {
|
||||
int j=i;
|
||||
Set<int> sequence=new Set<int>();
|
||||
while(happy[j]==null && !sequence.contains(j)) {
|
||||
sequence.add(j);
|
||||
int sum=0;
|
||||
int val=j;
|
||||
while(val>0) {
|
||||
int digit=val%10;
|
||||
sum+=digit*digit;
|
||||
val=(val/10).toInt();
|
||||
}
|
||||
j=sum;
|
||||
}
|
||||
bool sequenceHappy=happy[j];
|
||||
Iterator<int> it=sequence.iterator();
|
||||
while(it.hasNext()) {
|
||||
happy[it.next()]=sequenceHappy;
|
||||
}
|
||||
}
|
||||
if(happy[i]) {
|
||||
print(i);
|
||||
count++;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
20
Task/Happy-numbers/E/happy-numbers.e
Normal file
20
Task/Happy-numbers/E/happy-numbers.e
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
def isHappyNumber(var x :int) {
|
||||
var seen := [].asSet()
|
||||
while (!seen.contains(x)) {
|
||||
seen with= x
|
||||
var sum := 0
|
||||
while (x > 0) {
|
||||
sum += (x % 10) ** 2
|
||||
x //= 10
|
||||
}
|
||||
x := sum
|
||||
if (x == 1) { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var count := 0
|
||||
for x ? (isHappyNumber(x)) in (int >= 1) {
|
||||
println(x)
|
||||
if ((count += 1) >= 8) { break }
|
||||
}
|
||||
32
Task/Happy-numbers/Erlang/happy-numbers-1.erl
Normal file
32
Task/Happy-numbers/Erlang/happy-numbers-1.erl
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
-module(tasks).
|
||||
-export([main/0]).
|
||||
-import(lists, [map/2, member/2, sort/1, sum/1]).
|
||||
|
||||
is_happy(X, XS) ->
|
||||
if
|
||||
X == 1 ->
|
||||
true;
|
||||
X < 1 ->
|
||||
false;
|
||||
true ->
|
||||
case member(X, XS) of
|
||||
true -> false;
|
||||
false ->
|
||||
is_happy(sum(map(fun(Z) -> Z*Z end,
|
||||
[Y - 48 || Y <- integer_to_list(X)])),
|
||||
[X|XS])
|
||||
end
|
||||
end.
|
||||
|
||||
main(X, XS) ->
|
||||
if
|
||||
length(XS) == 8 ->
|
||||
io:format("8 Happy Numbers: ~w~n", [sort(XS)]);
|
||||
true ->
|
||||
case is_happy(X, []) of
|
||||
true -> main(X + 1, [X|XS]);
|
||||
false -> main(X + 1, XS)
|
||||
end
|
||||
end.
|
||||
main() ->
|
||||
main(0, []).
|
||||
1
Task/Happy-numbers/Erlang/happy-numbers-2.erl
Normal file
1
Task/Happy-numbers/Erlang/happy-numbers-2.erl
Normal file
|
|
@ -0,0 +1 @@
|
|||
erl -run tasks main -run init stop -noshell
|
||||
1
Task/Happy-numbers/Erlang/happy-numbers-3.erl
Normal file
1
Task/Happy-numbers/Erlang/happy-numbers-3.erl
Normal file
|
|
@ -0,0 +1 @@
|
|||
8 Happy Numbers: [1,7,10,13,19,23,28,31]
|
||||
18
Task/Happy-numbers/Erlang/happy-numbers-4.erl
Normal file
18
Task/Happy-numbers/Erlang/happy-numbers-4.erl
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
-module(tasks).
|
||||
|
||||
-export([main/0]).
|
||||
|
||||
main() -> io:format("~w ~n", [happy_list(1, 8, [])]).
|
||||
|
||||
happy_list(_, N, L) when length(L) =:= N -> lists:reverse(L);
|
||||
happy_list(X, N, L) ->
|
||||
Happy = is_happy(X),
|
||||
if Happy -> happy_list(X + 1, N, [X|L]);
|
||||
true -> happy_list(X + 1, N, L) end.
|
||||
|
||||
is_happy(1) -> true;
|
||||
is_happy(4) -> false;
|
||||
is_happy(N) when N > 0 ->
|
||||
N_As_Digits = [Y - 48 || Y <- integer_to_list(N)],
|
||||
is_happy(lists:foldl(fun(X, Sum) -> (X * X) + Sum end, 0, N_As_Digits));
|
||||
is_happy(_) -> false.
|
||||
29
Task/Happy-numbers/Euphoria/happy-numbers.euphoria
Normal file
29
Task/Happy-numbers/Euphoria/happy-numbers.euphoria
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
function is_happy(integer n)
|
||||
sequence seen
|
||||
integer k
|
||||
seen = {}
|
||||
while n > 1 do
|
||||
seen &= n
|
||||
k = 0
|
||||
while n > 0 do
|
||||
k += power(remainder(n,10),2)
|
||||
n = floor(n/10)
|
||||
end while
|
||||
n = k
|
||||
if find(n,seen) then
|
||||
return 0
|
||||
end if
|
||||
end while
|
||||
return 1
|
||||
end function
|
||||
|
||||
integer n,count
|
||||
n = 1
|
||||
count = 0
|
||||
while count < 8 do
|
||||
if is_happy(n) then
|
||||
? n
|
||||
count += 1
|
||||
end if
|
||||
n += 1
|
||||
end while
|
||||
21
Task/Happy-numbers/Factor/happy-numbers-1.factor
Normal file
21
Task/Happy-numbers/Factor/happy-numbers-1.factor
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
USING: combinators kernel make math sequences ;
|
||||
|
||||
: squares ( n -- s )
|
||||
0 [ over 0 > ] [ [ 10 /mod sq ] dip + ] while nip ;
|
||||
|
||||
: (happy?) ( n1 n2 -- ? )
|
||||
[ squares ] [ squares squares ] bi* {
|
||||
{ [ dup 1 = ] [ 2drop t ] }
|
||||
{ [ 2dup = ] [ 2drop f ] }
|
||||
[ (happy?) ]
|
||||
} cond ;
|
||||
|
||||
: happy? ( n -- ? )
|
||||
dup (happy?) ;
|
||||
|
||||
: happy-numbers ( n -- seq )
|
||||
[
|
||||
0 [ over 0 > ] [
|
||||
dup happy? [ dup , [ 1 - ] dip ] when 1 +
|
||||
] while 2drop
|
||||
] { } make ;
|
||||
1
Task/Happy-numbers/Factor/happy-numbers-2.factor
Normal file
1
Task/Happy-numbers/Factor/happy-numbers-2.factor
Normal file
|
|
@ -0,0 +1 @@
|
|||
8 happy-numbers ! { 1 7 10 13 19 23 28 31 }
|
||||
35
Task/Happy-numbers/Fantom/happy-numbers.fantom
Normal file
35
Task/Happy-numbers/Fantom/happy-numbers.fantom
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
class Main
|
||||
{
|
||||
static Bool isHappy (Int n)
|
||||
{
|
||||
Int[] record := [,]
|
||||
while (n != 1 && !record.contains(n))
|
||||
{
|
||||
record.add (n)
|
||||
// find sum of squares of digits
|
||||
newn := 0
|
||||
while (n > 0)
|
||||
{
|
||||
newn += (n.mod(10) * n.mod(10))
|
||||
n = n.div(10)
|
||||
}
|
||||
n = newn
|
||||
}
|
||||
return (n == 1)
|
||||
}
|
||||
|
||||
public static Void main ()
|
||||
{
|
||||
i := 1
|
||||
count := 0
|
||||
while (count < 8)
|
||||
{
|
||||
if (isHappy (i))
|
||||
{
|
||||
echo (i)
|
||||
count += 1
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
20
Task/Happy-numbers/Forth/happy-numbers.fth
Normal file
20
Task/Happy-numbers/Forth/happy-numbers.fth
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
: next ( n -- n )
|
||||
0 swap begin 10 /mod >r dup * + r> ?dup 0= until ;
|
||||
|
||||
: cycle? ( n -- ? )
|
||||
here dup @ cells +
|
||||
begin dup here >
|
||||
while 2dup @ = if 2drop true exit then
|
||||
1 cells -
|
||||
repeat
|
||||
1 over +! dup @ cells + ! false ;
|
||||
|
||||
: happy? ( n -- ? )
|
||||
0 here ! begin next dup cycle? until 1 = ;
|
||||
|
||||
: happy-numbers ( n -- )
|
||||
0 swap 0 do
|
||||
begin 1+ dup happy? until dup .
|
||||
loop drop ;
|
||||
|
||||
8 happy-numbers \ 1 7 10 13 19 23 28 31
|
||||
67
Task/Happy-numbers/Fortran/happy-numbers.f
Normal file
67
Task/Happy-numbers/Fortran/happy-numbers.f
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
program happy
|
||||
|
||||
implicit none
|
||||
integer, parameter :: find = 8
|
||||
integer :: found
|
||||
integer :: number
|
||||
|
||||
found = 0
|
||||
number = 1
|
||||
do
|
||||
if (found == find) then
|
||||
exit
|
||||
end if
|
||||
if (is_happy (number)) then
|
||||
found = found + 1
|
||||
write (*, '(i0)') number
|
||||
end if
|
||||
number = number + 1
|
||||
end do
|
||||
|
||||
contains
|
||||
|
||||
function sum_digits_squared (number) result (result)
|
||||
|
||||
implicit none
|
||||
integer, intent (in) :: number
|
||||
integer :: result
|
||||
integer :: digit
|
||||
integer :: rest
|
||||
integer :: work
|
||||
|
||||
result = 0
|
||||
work = number
|
||||
do
|
||||
if (work == 0) then
|
||||
exit
|
||||
end if
|
||||
rest = work / 10
|
||||
digit = work - 10 * rest
|
||||
result = result + digit * digit
|
||||
work = rest
|
||||
end do
|
||||
|
||||
end function sum_digits_squared
|
||||
|
||||
function is_happy (number) result (result)
|
||||
|
||||
implicit none
|
||||
integer, intent (in) :: number
|
||||
logical :: result
|
||||
integer :: turtoise
|
||||
integer :: hare
|
||||
|
||||
turtoise = number
|
||||
hare = number
|
||||
do
|
||||
turtoise = sum_digits_squared (turtoise)
|
||||
hare = sum_digits_squared (sum_digits_squared (hare))
|
||||
if (turtoise == hare) then
|
||||
exit
|
||||
end if
|
||||
end do
|
||||
result = turtoise == 1
|
||||
|
||||
end function is_happy
|
||||
|
||||
end program happy
|
||||
17
Task/Happy-numbers/Frege/happy-numbers.frege
Normal file
17
Task/Happy-numbers/Frege/happy-numbers.frege
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
module Happy where
|
||||
|
||||
import Prelude.Math
|
||||
-- ugh, since Frege doesn't have Set, use Map instead
|
||||
import Data.Map (member, insertMin, empty)
|
||||
|
||||
digitToInteger :: Char -> Integer
|
||||
digitToInteger c = fromInt $ (ord c) - (ord '0')
|
||||
|
||||
isHappy :: Integer -> Bool
|
||||
isHappy = p empty
|
||||
where p _ 1n = true
|
||||
p s n | n `member` s = false
|
||||
| otherwise = p (insertMin n () s) (f n)
|
||||
f = sum . map (sqr . digitToInteger) . unpacked . show
|
||||
|
||||
main _ = printStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n
|
||||
33
Task/Happy-numbers/Go/happy-numbers.go
Normal file
33
Task/Happy-numbers/Go/happy-numbers.go
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func happy(n int) bool {
|
||||
m := make(map[int]int)
|
||||
for n > 1 {
|
||||
m[n] = 0
|
||||
s := strconv.Itoa(n)
|
||||
n = 0
|
||||
for _, d := range s {
|
||||
x := int(d) - '0'
|
||||
n += x * x
|
||||
}
|
||||
if _, ok := m[n]; ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func main() {
|
||||
for found, n := 0, 1; found < 8; n++ {
|
||||
if happy(n) {
|
||||
fmt.Print(n, " ")
|
||||
found++
|
||||
}
|
||||
}
|
||||
fmt.Println("")
|
||||
}
|
||||
11
Task/Happy-numbers/Haskell/happy-numbers-1.hs
Normal file
11
Task/Happy-numbers/Haskell/happy-numbers-1.hs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import Data.Char (digitToInt)
|
||||
import Data.Set (member, insert, empty)
|
||||
|
||||
isHappy :: Integer -> Bool
|
||||
isHappy = p empty
|
||||
where p _ 1 = True
|
||||
p s n | n `member` s = False
|
||||
| otherwise = p (insert n s) (f n)
|
||||
f = sum . map ((^2) . toInteger . digitToInt) . show
|
||||
|
||||
main = mapM_ print $ take 8 $ filter isHappy [1..]
|
||||
10
Task/Happy-numbers/Haskell/happy-numbers-2.hs
Normal file
10
Task/Happy-numbers/Haskell/happy-numbers-2.hs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import Data.Array
|
||||
|
||||
happy x = if xx <= 150 then seen!xx else happy xx where
|
||||
xx = dsum x
|
||||
seen :: Array Int Bool
|
||||
seen = listArray (1,150) $ True:False:False:False:(map happy [5..150])
|
||||
dsum n | n < 10 = n * n
|
||||
| otherwise = let (q,r) = n `divMod` 10 in r*r + dsum q
|
||||
|
||||
main = print $ sum $ take 10000 $ filter happy [1..]
|
||||
17
Task/Happy-numbers/Icon/happy-numbers.icon
Normal file
17
Task/Happy-numbers/Icon/happy-numbers.icon
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
procedure main(arglist)
|
||||
local n
|
||||
n := arglist[1] | 8 # limiting number of happy numbers to generate, default=8
|
||||
writes("The first ",n," happy numbers are:")
|
||||
every writes(" ", happy(seq()) \ n )
|
||||
write()
|
||||
end
|
||||
|
||||
procedure happy(i) #: returns i if i is happy
|
||||
local n
|
||||
|
||||
if 4 ~= (0 <= i) then { # unhappy if negative, 0, or 4
|
||||
if i = 1 then return i
|
||||
every (n := 0) +:= !i ^ 2
|
||||
if happy(n) then return i
|
||||
}
|
||||
end
|
||||
2
Task/Happy-numbers/J/happy-numbers-1.j
Normal file
2
Task/Happy-numbers/J/happy-numbers-1.j
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
8{. (#~1=+/@(*:@(,.&.":))^:(1&~:*.4&~:)^:_ "0) 1+i.100
|
||||
1 7 10 13 19 23 28 31
|
||||
1
Task/Happy-numbers/J/happy-numbers-2.j
Normal file
1
Task/Happy-numbers/J/happy-numbers-2.j
Normal file
|
|
@ -0,0 +1 @@
|
|||
f ^: cond ^: _ input
|
||||
1
Task/Happy-numbers/J/happy-numbers-3.j
Normal file
1
Task/Happy-numbers/J/happy-numbers-3.j
Normal file
|
|
@ -0,0 +1 @@
|
|||
(binary array) # 1..100
|
||||
7
Task/Happy-numbers/J/happy-numbers-4.j
Normal file
7
Task/Happy-numbers/J/happy-numbers-4.j
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
cond=: 1&~: *. 4&~: NB. not equal to 1 and not equal to 4
|
||||
sumSqrDigits=: +/@(*:@(,.&.":))
|
||||
|
||||
sumSqrDigits 123 NB. test sum of squared digits
|
||||
14
|
||||
8{. (#~ 1 = sumSqrDigits ^: cond ^:_ "0) 1 + i.100
|
||||
1 7 10 13 19 23 28 31
|
||||
27
Task/Happy-numbers/Java/happy-numbers.java
Normal file
27
Task/Happy-numbers/Java/happy-numbers.java
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import java.util.HashSet;
|
||||
public class Happy{
|
||||
public static boolean happy(long number){
|
||||
long m = 0;
|
||||
int digit = 0;
|
||||
HashSet<Long> cycle = new HashSet<Long>();
|
||||
while(number != 1 && cycle.add(number)){
|
||||
m = 0;
|
||||
while(number > 0){
|
||||
digit = (int)(number % 10);
|
||||
m += digit*digit;
|
||||
number /= 10;
|
||||
}
|
||||
number = m;
|
||||
}
|
||||
return number == 1;
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
for(long num = 1,count = 0;count<8;num++){
|
||||
if(happy(num)){
|
||||
System.out.println(num);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
26
Task/Happy-numbers/JavaScript/happy-numbers.js
Normal file
26
Task/Happy-numbers/JavaScript/happy-numbers.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
function happy(number) {
|
||||
var m, digit ;
|
||||
var cycle = [] ;
|
||||
|
||||
while(number != 1 && cycle[number] !== true) {
|
||||
cycle[number] = true ;
|
||||
m = 0 ;
|
||||
while (number > 0) {
|
||||
digit = number % 10 ;
|
||||
m += digit * digit ;
|
||||
number = (number - digit) / 10 ;
|
||||
}
|
||||
number = m ;
|
||||
}
|
||||
return (number == 1) ;
|
||||
}
|
||||
|
||||
var cnt = 8 ;
|
||||
var number = 1 ;
|
||||
|
||||
while(cnt-- > 0) {
|
||||
while(!happy(number))
|
||||
number++ ;
|
||||
document.write(number + " ") ;
|
||||
number++ ;
|
||||
}
|
||||
15
Task/Happy-numbers/Julia/happy-numbers.julia
Normal file
15
Task/Happy-numbers/Julia/happy-numbers.julia
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
function happy(x)
|
||||
happy_ints = ref(Int)
|
||||
int_try = 1
|
||||
while length(happy_ints) < x
|
||||
n = int_try
|
||||
past = ref(Int)
|
||||
while n != 1
|
||||
n = sum([int(string(y))^2 for y in string(n)])
|
||||
contains(past,n) ? break : push!(past,n)
|
||||
end
|
||||
if n == 1 push!(happy_ints,int_try) end
|
||||
int_try += 1
|
||||
end
|
||||
return happy_ints
|
||||
end
|
||||
7
Task/Happy-numbers/K/happy-numbers.k
Normal file
7
Task/Happy-numbers/K/happy-numbers.k
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
hpy: {x@&1={~|/x=1 4}{_+/_sqr 0$'$x}//:x}
|
||||
|
||||
hpy 1+!100
|
||||
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100
|
||||
|
||||
8#hpy 1+!100
|
||||
1 7 10 13 19 23 28 31
|
||||
28
Task/Happy-numbers/Liberty-BASIC/happy-numbers.liberty
Normal file
28
Task/Happy-numbers/Liberty-BASIC/happy-numbers.liberty
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
ct = 0
|
||||
n = 0
|
||||
DO
|
||||
n = n + 1
|
||||
IF HappyN(n, sqrInt$) = 1 THEN
|
||||
ct = ct + 1
|
||||
PRINT ct, n
|
||||
END IF
|
||||
LOOP UNTIL ct = 8
|
||||
END
|
||||
|
||||
FUNCTION HappyN(n, sqrInts$)
|
||||
n$ = Str$(n)
|
||||
sqrInts = 0
|
||||
FOR i = 1 TO Len(n$)
|
||||
sqrInts = sqrInts + Val(Mid$(n$, i, 1)) ^ 2
|
||||
NEXT i
|
||||
IF sqrInts = 1 THEN
|
||||
HappyN = 1
|
||||
EXIT FUNCTION
|
||||
END IF
|
||||
IF Instr(sqrInts$, ":";Str$(sqrInts);":") > 0 THEN
|
||||
HappyN = 0
|
||||
EXIT FUNCTION
|
||||
END IF
|
||||
sqrInts$ = sqrInts$ + Str$(sqrInts) + ":"
|
||||
HappyN = HappyN(sqrInts, sqrInts$)
|
||||
END FUNCTION
|
||||
16
Task/Happy-numbers/Locomotive-Basic/happy-numbers.bas
Normal file
16
Task/Happy-numbers/Locomotive-Basic/happy-numbers.bas
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
10 mode 1:defint a-z
|
||||
20 for i=1 to 100
|
||||
30 i2=i
|
||||
40 for l=1 to 20
|
||||
50 a$=str$(i2)
|
||||
60 i2=0
|
||||
70 for j=1 to len(a$)
|
||||
80 d=val(mid$(a$,j,1))
|
||||
90 i2=i2+d*d
|
||||
100 next j
|
||||
110 if i2=1 then print i;"is a happy number":n=n+1:goto 150
|
||||
120 if i2=4 then 150 ' cycle found
|
||||
130 next l
|
||||
140 ' check if we have reached 8 numbers yet
|
||||
150 if n=8 then end
|
||||
160 next i
|
||||
24
Task/Happy-numbers/Logo/happy-numbers.logo
Normal file
24
Task/Happy-numbers/Logo/happy-numbers.logo
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
to sum_of_square_digits :number
|
||||
output (apply "sum (map [[d] d*d] ` :number))
|
||||
end
|
||||
|
||||
to is_happy? :number [:seen []]
|
||||
output cond [
|
||||
[ [:number = 1] "true ]
|
||||
[ [member? :number :seen] "false ]
|
||||
[ else (is_happy? (sum_of_square_digits :number) (lput :number :seen))]
|
||||
]
|
||||
end
|
||||
|
||||
to n_happy :count [:start 1] [:result []]
|
||||
output cond [
|
||||
[ [:count <= 0] :result ]
|
||||
[ [is_happy? :start]
|
||||
(n_happy (:count-1) (:start+1) (lput :start :result)) ]
|
||||
[ else
|
||||
(n_happy :count (:start+1) :result) ]
|
||||
]
|
||||
end
|
||||
|
||||
print n_happy 8
|
||||
bye
|
||||
15
Task/Happy-numbers/Lua/happy-numbers.lua
Normal file
15
Task/Happy-numbers/Lua/happy-numbers.lua
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
function digits(n)
|
||||
if n > 0 then return n % 10, digits(math.floor(n/10)) end
|
||||
end
|
||||
function sumsq(a, ...)
|
||||
return a and a ^ 2 + sumsq(...) or 0
|
||||
end
|
||||
local happy = setmetatable({true, false, false, false}, {
|
||||
__index = function(self, n)
|
||||
self[n] = self[sumsq(digits(n))]
|
||||
return self[n]
|
||||
end } )
|
||||
i, j = 0, 1
|
||||
repeat
|
||||
i, j = happy[j] and (print(j) or i+1) or i, j + 1
|
||||
until i == 8
|
||||
24
Task/Happy-numbers/MUMPS/happy-numbers.mumps
Normal file
24
Task/Happy-numbers/MUMPS/happy-numbers.mumps
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
ISHAPPY(N)
|
||||
;Determines if a number N is a happy number
|
||||
;Note that the returned strings do not have a leading digit unless it is a happy number
|
||||
IF (N'=N\1)!(N<0) QUIT "Not a positive integer"
|
||||
NEW SUM,I
|
||||
;SUM is the sum of the square of each digit
|
||||
;I is a loop variable
|
||||
;SEQ is the sequence of previously checked SUMs from the original N
|
||||
;If it isn't set already, initialize it to an empty string
|
||||
IF $DATA(SEQ)=0 NEW SEQ SET SEQ=""
|
||||
SET SUM=0
|
||||
FOR I=1:1:$LENGTH(N) DO
|
||||
.SET SUM=SUM+($EXTRACT(N,I)*$EXTRACT(N,I))
|
||||
QUIT:(SUM=1) SUM
|
||||
QUIT:$FIND(SEQ,SUM)>1 "Part of a sequence not containing 1"
|
||||
SET SEQ=SEQ_","_SUM
|
||||
QUIT $$ISHAPPY(SUM)
|
||||
HAPPY(C) ;Finds the first C happy numbers
|
||||
NEW I
|
||||
;I is a counter for what integer we're looking at
|
||||
WRITE !,"The first "_C_" happy numbers are:"
|
||||
FOR I=1:1 QUIT:C<1 SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1
|
||||
KILL I
|
||||
QUIT
|
||||
8
Task/Happy-numbers/Maple/happy-numbers-1.maple
Normal file
8
Task/Happy-numbers/Maple/happy-numbers-1.maple
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
SumSqDigits := proc( n :: posint )
|
||||
local s := 0;
|
||||
local m := n;
|
||||
while m <> 0 do
|
||||
s := s + irem( m, 10, 'm' )^2
|
||||
end do;
|
||||
s
|
||||
end proc:
|
||||
2
Task/Happy-numbers/Maple/happy-numbers-2.maple
Normal file
2
Task/Happy-numbers/Maple/happy-numbers-2.maple
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
> SumSqDigits( 1234567890987654321 );
|
||||
570
|
||||
3
Task/Happy-numbers/Maple/happy-numbers-3.maple
Normal file
3
Task/Happy-numbers/Maple/happy-numbers-3.maple
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
> n := 1234567890987654321:
|
||||
> `+`( op( map( parse, StringTools:-Explode( convert( n, 'string' ) ) )^~2) );
|
||||
570
|
||||
13
Task/Happy-numbers/Maple/happy-numbers-4.maple
Normal file
13
Task/Happy-numbers/Maple/happy-numbers-4.maple
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
Happy? := proc( n )
|
||||
if n = 1 then
|
||||
true
|
||||
elif n = 4 then
|
||||
false
|
||||
else
|
||||
local s := SumSqDigits( n );
|
||||
while not ( s in { 1, 4 } ) do
|
||||
s := SumSqDigits( s )
|
||||
end do;
|
||||
evalb( s = 1 )
|
||||
end if
|
||||
end proc:
|
||||
3
Task/Happy-numbers/Maple/happy-numbers-5.maple
Normal file
3
Task/Happy-numbers/Maple/happy-numbers-5.maple
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
> H, S := selectremove( Happy?, [seq]( 1 .. N ) ):
|
||||
> nops( H ), nops( S );
|
||||
143071, 856929
|
||||
11
Task/Happy-numbers/Maple/happy-numbers-6.maple
Normal file
11
Task/Happy-numbers/Maple/happy-numbers-6.maple
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
FindHappiness := proc( N )
|
||||
local count := 0;
|
||||
local T := table();
|
||||
for local i while count < N do
|
||||
if Happy?( i ) then
|
||||
count := 1 + count;
|
||||
T[ count ] := i
|
||||
end if
|
||||
end do;
|
||||
{seq}( T[ i ], i = 1 .. count )
|
||||
end proc:
|
||||
2
Task/Happy-numbers/Maple/happy-numbers-7.maple
Normal file
2
Task/Happy-numbers/Maple/happy-numbers-7.maple
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
> FindHappiness( 8 );
|
||||
{1, 7, 10, 13, 19, 23, 28, 31}
|
||||
9
Task/Happy-numbers/Maple/happy-numbers-8.maple
Normal file
9
Task/Happy-numbers/Maple/happy-numbers-8.maple
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
Happy? := proc( n :: posint )
|
||||
local a, b;
|
||||
a, b := n, SumSqDigits( n );
|
||||
while a <> b do
|
||||
a := SumSqDigits( a );
|
||||
b := (SumSqDigits@@2)( b )
|
||||
end do;
|
||||
evalb( a = 1 )
|
||||
end proc:
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
AddSumSquare[input_]:=Append[input,Total[IntegerDigits[Last[input]]^2]]
|
||||
NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All]
|
||||
HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
HappyQ[1337]
|
||||
HappyQ[137]
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
True
|
||||
False
|
||||
12
Task/Happy-numbers/Mathematica/happy-numbers-4.mathematica
Normal file
12
Task/Happy-numbers/Mathematica/happy-numbers-4.mathematica
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
m = 8;
|
||||
n = 1;
|
||||
i = 0;
|
||||
happynumbers = {};
|
||||
While[n <= m,
|
||||
i++;
|
||||
If[HappyQ[i],
|
||||
n++;
|
||||
AppendTo[happynumbers, i]
|
||||
]
|
||||
]
|
||||
happynumbers
|
||||
|
|
@ -0,0 +1 @@
|
|||
{1, 7, 10, 13, 19, 23, 28, 31}
|
||||
24
Task/Happy-numbers/PHP/happy-numbers.php
Normal file
24
Task/Happy-numbers/PHP/happy-numbers.php
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
function isHappy($n) {
|
||||
while (1) {
|
||||
$total = 0;
|
||||
while ($n > 0) {
|
||||
$total += pow(($n % 10), 2);
|
||||
$n /= 10;
|
||||
}
|
||||
if ($total == 1)
|
||||
return true;
|
||||
if (array_key_exists($total, $past))
|
||||
return false;
|
||||
$n = $total;
|
||||
$past[$total] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
$i = $cnt = 0;
|
||||
while ($cnt < 8) {
|
||||
if (isHappy($i)) {
|
||||
echo "$i ";
|
||||
$cnt++;
|
||||
}
|
||||
$i++;
|
||||
}
|
||||
11
Task/Happy-numbers/Perl/happy-numbers.pl
Normal file
11
Task/Happy-numbers/Perl/happy-numbers.pl
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
use List::Util qw(sum);
|
||||
|
||||
sub is_happy ($)
|
||||
{for (my ($n, %seen) = shift ;; $n = sum map {$_**2} split //, $n)
|
||||
{$n == 1 and return 1;
|
||||
$seen{$n}++ and return 0;}}
|
||||
|
||||
for (my ($n, $happy) = (1, 0) ; $happy < 8 ; ++$n)
|
||||
{is_happy $n or next;
|
||||
print "$n\n";
|
||||
++$happy;}
|
||||
13
Task/Happy-numbers/PicoLisp/happy-numbers.l
Normal file
13
Task/Happy-numbers/PicoLisp/happy-numbers.l
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
(de happy? (N)
|
||||
(let Seen NIL
|
||||
(loop
|
||||
(T (= N 1) T)
|
||||
(T (member N Seen))
|
||||
(setq N
|
||||
(sum '((C) (** (format C) 2))
|
||||
(chop (push 'Seen N)) ) ) ) ) )
|
||||
|
||||
(let H 0
|
||||
(do 8
|
||||
(until (happy? (inc 'H)))
|
||||
(printsp H) ) )
|
||||
47
Task/Happy-numbers/Prolog/happy-numbers-1.pro
Normal file
47
Task/Happy-numbers/Prolog/happy-numbers-1.pro
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
happy_numbers(L, Nb) :-
|
||||
% creation of the list
|
||||
length(L, Nb),
|
||||
% Process of this list
|
||||
get_happy_number(L, 1).
|
||||
|
||||
|
||||
% the game is over
|
||||
get_happy_number([], _).
|
||||
|
||||
% querying the newt happy_number
|
||||
get_happy_number([H | T], N) :-
|
||||
N1 is N+1,
|
||||
(is_happy_number(N) ->
|
||||
H = N,
|
||||
get_happy_number(T, N1);
|
||||
get_happy_number([H | T], N1)).
|
||||
|
||||
% we must memorized the numbers reached
|
||||
is_happy_number(N) :-
|
||||
is_happy_number(N, [N]).
|
||||
|
||||
% a number is happy when we get 1
|
||||
is_happy_number(N, _L) :-
|
||||
get_next_number(N, 1), !.
|
||||
|
||||
% or when this number is not already reached !
|
||||
is_happy_number(N, L) :-
|
||||
get_next_number(N, NN),
|
||||
\+member(NN, L),
|
||||
is_happy_number(NN, [NN | L]).
|
||||
|
||||
% Process of the next number from N
|
||||
get_next_number(N, NewN) :-
|
||||
get_list_digits(N, LD),
|
||||
maplist(square, LD, L),
|
||||
sumlist(L, NewN).
|
||||
|
||||
get_list_digits(N, LD) :-
|
||||
number_chars(N, LCD),
|
||||
maplist(number_chars_, LD, LCD).
|
||||
|
||||
number_chars_(D, CD) :-
|
||||
number_chars(D, [CD]).
|
||||
|
||||
square(N, SN) :-
|
||||
SN is N * N.
|
||||
2
Task/Happy-numbers/Prolog/happy-numbers-2.pro
Normal file
2
Task/Happy-numbers/Prolog/happy-numbers-2.pro
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
?- happy_numbers(L, 8).
|
||||
L = [1,7,10,13,19,23,28,31].
|
||||
11
Task/Happy-numbers/Python/happy-numbers.py
Normal file
11
Task/Happy-numbers/Python/happy-numbers.py
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
>>> def happy(n):
|
||||
past = set()
|
||||
while n <> 1:
|
||||
n = sum(int(i)**2 for i in str(n))
|
||||
if n in past:
|
||||
return False
|
||||
past.add(n)
|
||||
return True
|
||||
|
||||
>>> [x for x in xrange(500) if happy(x)][:8]
|
||||
[1, 7, 10, 13, 19, 23, 28, 31]
|
||||
29
Task/Happy-numbers/R/happy-numbers-1.r
Normal file
29
Task/Happy-numbers/R/happy-numbers-1.r
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
is.happy <- function(n)
|
||||
{
|
||||
stopifnot(is.numeric(n) && length(n)==1)
|
||||
getdigits <- function(n)
|
||||
{
|
||||
as.integer(unlist(strsplit(as.character(n), "")))
|
||||
}
|
||||
digits <- getdigits(n)
|
||||
previous <- c()
|
||||
repeat
|
||||
{
|
||||
sumsq <- sum(digits^2, na.rm=TRUE)
|
||||
if(sumsq==1L)
|
||||
{
|
||||
happy <- TRUE
|
||||
break
|
||||
} else if(sumsq %in% previous)
|
||||
{
|
||||
happy <- FALSE
|
||||
attr(happy, "cycle") <- previous
|
||||
break
|
||||
} else
|
||||
{
|
||||
previous <- c(previous, sumsq)
|
||||
digits <- getdigits(sumsq)
|
||||
}
|
||||
}
|
||||
happy
|
||||
}
|
||||
1
Task/Happy-numbers/R/happy-numbers-2.r
Normal file
1
Task/Happy-numbers/R/happy-numbers-2.r
Normal file
|
|
@ -0,0 +1 @@
|
|||
is.happy(2)
|
||||
2
Task/Happy-numbers/R/happy-numbers-3.r
Normal file
2
Task/Happy-numbers/R/happy-numbers-3.r
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
#Find happy numbers between 1 and 50
|
||||
which(apply(rbind(1:50), 2, is.happy))
|
||||
9
Task/Happy-numbers/R/happy-numbers-4.r
Normal file
9
Task/Happy-numbers/R/happy-numbers-4.r
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
#Find the first 8 happy numbers
|
||||
happies <- c()
|
||||
i <- 1L
|
||||
while(length(happies) < 8L)
|
||||
{
|
||||
if(is.happy(i)) happies <- c(happies, i)
|
||||
i <- i + 1L
|
||||
}
|
||||
happies
|
||||
19
Task/Happy-numbers/REXX/happy-numbers-1.rexx
Normal file
19
Task/Happy-numbers/REXX/happy-numbers-1.rexx
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
/*REXX program displays eight (or a specified limit) happy numbers. */
|
||||
parse arg limit . /*get optional argument LIMIT. */
|
||||
if limit=='' | limit==',' then limit=8 /*Not specified? Set LIMIT to 8.*/
|
||||
haps=0 /*count of happy numbers so far. */
|
||||
|
||||
do n=1 while haps<limit; q=n; a.=0 /*search integers starting at 1.*/
|
||||
do until q==1 /*see if Q is a happy number.*/
|
||||
s=0 /*prepare to add squares of digs.*/
|
||||
do j=1 for length(q) /*sum the squares of the digits. */
|
||||
s=s+substr(q,j,1)**2 /*add the square of a digit. */
|
||||
end /*j*/
|
||||
|
||||
if a.s then iterate n /*if already summed, Q is unhappy*/
|
||||
a.s=1; q=s /*mark sum as found, try Q sum.*/
|
||||
end /*until*/
|
||||
say n /*display the number (N is happy)*/
|
||||
haps=haps+1 /*bump the count of happy numbers*/
|
||||
end /*n*/
|
||||
/*stick a fork in it, we're done.*/
|
||||
31
Task/Happy-numbers/REXX/happy-numbers-2.rexx
Normal file
31
Task/Happy-numbers/REXX/happy-numbers-2.rexx
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/*REXX program displays eight (or a specified range of) happy numbers.*/
|
||||
parse arg L H . /*get optional args: low & high */
|
||||
if L=='' | L==',' then L=8 /*Not specified? Set L to default*/
|
||||
if H=='' | H==',' then do; H=L; L=1; end /*use a range for the showing.*/
|
||||
haps=0 /*count of happy numbers so far. */
|
||||
@.=0; !.=0 /*sparse array: happy&unhappy #s.*/
|
||||
|
||||
do n=1 while haps<H; q=n; a.=0 /*search integers starting at 1.*/
|
||||
if !.n then iterate /*if N is unhappy, try another.*/
|
||||
|
||||
do until q==1 /*see if Q is a happy number. */
|
||||
s=0 /*prepare to add squares of digs.*/
|
||||
do j=1 for length(q) /*sum the squares of the digits. */
|
||||
s=s+substr(q,j,1)**2 /*add the square of a digit. */
|
||||
end /*j*/
|
||||
|
||||
if @.s then do; q=1; iterate; end /*we have found a happy number.*/
|
||||
if !.s then iterate n /*Sum unhappy? Then Q is unhappy*/
|
||||
if a.s then do /*If already summed? Q is unhappy*/
|
||||
!.q=1; !.s=1 /*mark Q & S as unhappy numbers*/
|
||||
iterate n /*previously summed, so Q unhappy*/
|
||||
end
|
||||
a.s=1; q=s /*mark sum as found, try Q sum.*/
|
||||
end /*until*/
|
||||
|
||||
@.n=1 /*mark N as a happy number. */
|
||||
haps=haps+1 /*bump the count of happy numbers*/
|
||||
if haps<L then iterate /*don't display, N is too low. */
|
||||
say n /*display the happy N number.*/
|
||||
end /*n*/
|
||||
/*stick a fork in it, we're done.*/
|
||||
39
Task/Happy-numbers/REXX/happy-numbers-3.rexx
Normal file
39
Task/Happy-numbers/REXX/happy-numbers-3.rexx
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
/*REXX program displays eight (or a specified range of) happy numbers.*/
|
||||
parse arg L H . /*get optional args: low & high */
|
||||
if L=='' | L==',' then L=8 /*Not specified? Set L to default*/
|
||||
if H=='' | H==',' then do; H=L; L=1; end /*use a range for the showing.*/
|
||||
haps=0 /*count of happy numbers so far. */
|
||||
@.=0; !.=0 /*sparse array: happy&unhappy #s.*/
|
||||
out= /*the output line (of happy nums)*/
|
||||
sw=linesize() /*obtain the linesize of term scr*/
|
||||
|
||||
do n=1 while haps<H; q=n; a.=0 /*search integers starting at 1.*/
|
||||
if !.n then iterate /*if N is unhappy, try another.*/
|
||||
|
||||
do until q==1 /*see if Q is a happy number. */
|
||||
s=0 /*prepare to add squares of digs.*/
|
||||
do j=1 for length(q) /*sum the squares of the digits. */
|
||||
s=s+substr(q,j,1)**2 /*add the square of a digit. */
|
||||
end /*j*/
|
||||
|
||||
if @.s then do; q=1; iterate; end /*we have found a happy number.*/
|
||||
if !.s then iterate n /*Sum unhappy? Then Q is unhappy*/
|
||||
if a.s then do /*If already summed? Q is unhappy*/
|
||||
!.q=1; !.s=1 /*mark Q & S as unhappy numbers*/
|
||||
iterate n /*if already summed, Q is unhappy*/
|
||||
end
|
||||
a.s=1; q=s /*mark sum as found, try Q sum.*/
|
||||
end /*until*/
|
||||
|
||||
@.n=1 /*mark N as a happy number. */
|
||||
haps=haps+1 /*bump the count of happy numbers*/
|
||||
if haps<L then iterate /*don't display, N is too low. */
|
||||
if length(out n)>sw then do /*maybe display the happy number.*/
|
||||
say strip(out) /*line is too long, tell it*/
|
||||
out= /*nullify the OUT (line).*/
|
||||
end
|
||||
out=out n /*append the happy number to OUT.*/
|
||||
end /*n*/
|
||||
|
||||
if out\=='' then say strip(out) /*handle any residuals for OUT. */
|
||||
/*stick a fork in it, we're done.*/
|
||||
19
Task/Happy-numbers/Ruby/happy-numbers-1.rb
Normal file
19
Task/Happy-numbers/Ruby/happy-numbers-1.rb
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
require 'set' # Set: Fast array lookup / Simple existence hash
|
||||
|
||||
@seen_numbers = Set.new
|
||||
@happy_numbers = Set.new
|
||||
|
||||
def happy?(n)
|
||||
return true if n == 1 # Base case
|
||||
return @happy_numbers.include?(n) if @seen_numbers.include?(n) # Use performance cache, and stop unhappy cycles
|
||||
|
||||
@seen_numbers << n
|
||||
digit_squared_sum = n.to_s.each_char.inject(0) { |sum, c| sum + c.to_i**2 } # In Rails: n.to_s.each_char.sum { c.to_i**2 }
|
||||
|
||||
if happy?(digit_squared_sum)
|
||||
@happy_numbers << n
|
||||
true # Return true
|
||||
else
|
||||
false # Return false
|
||||
end
|
||||
end
|
||||
10
Task/Happy-numbers/Ruby/happy-numbers-2.rb
Normal file
10
Task/Happy-numbers/Ruby/happy-numbers-2.rb
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
def print_happy
|
||||
happy_numbers = []
|
||||
|
||||
(1..Float::INFINITY).each do |i|
|
||||
break if happy_numbers.length >= 8
|
||||
happy_numbers << i if happy?(i)
|
||||
end
|
||||
|
||||
p happy_numbers
|
||||
end
|
||||
1
Task/Happy-numbers/Ruby/happy-numbers-3.rb
Normal file
1
Task/Happy-numbers/Ruby/happy-numbers-3.rb
Normal file
|
|
@ -0,0 +1 @@
|
|||
[1, 7, 10, 13, 19, 23, 28, 31]
|
||||
24
Task/Happy-numbers/Scala/happy-numbers.scala
Normal file
24
Task/Happy-numbers/Scala/happy-numbers.scala
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
scala> def isHappy(n: Int) = {
|
||||
| new Iterator[Int] {
|
||||
| val seen = scala.collection.mutable.Set[Int]()
|
||||
| var curr = n
|
||||
| def next = {
|
||||
| val res = curr
|
||||
| curr = res.toString.map(_.asDigit).map(n => n * n).sum
|
||||
| seen += res
|
||||
| res
|
||||
| }
|
||||
| def hasNext = !seen.contains(curr)
|
||||
| }.toList.last == 1
|
||||
| }
|
||||
isHappy: (n: Int)Boolean
|
||||
|
||||
scala> Iterator from 1 filter isHappy take 8 foreach println
|
||||
1
|
||||
7
|
||||
10
|
||||
13
|
||||
19
|
||||
23
|
||||
28
|
||||
31
|
||||
17
Task/Happy-numbers/Scheme/happy-numbers.ss
Normal file
17
Task/Happy-numbers/Scheme/happy-numbers.ss
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
(define (number->list num)
|
||||
(do ((num num (quotient num 10))
|
||||
(lst '() (cons (remainder num 10) lst)))
|
||||
((zero? num) lst)))
|
||||
|
||||
(define (happy? num)
|
||||
(let loop ((num num) (seen '()))
|
||||
(cond ((= num 1) #t)
|
||||
((memv num seen) #f)
|
||||
(else (loop (apply + (map (lambda (x) (* x x)) (number->list num)))
|
||||
(cons num seen))))))
|
||||
|
||||
(display "happy numbers:")
|
||||
(let loop ((n 1) (more 8))
|
||||
(cond ((= more 0) (newline))
|
||||
((happy? n) (display " ") (display n) (loop (+ n 1) (- more 1)))
|
||||
(else (loop (+ n 1) more))))
|
||||
63
Task/Happy-numbers/Smalltalk/happy-numbers-1.st
Normal file
63
Task/Happy-numbers/Smalltalk/happy-numbers-1.st
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
Object subclass: HappyNumber [
|
||||
|cache negativeCache|
|
||||
HappyNumber class >> new [ |me|
|
||||
me := super new.
|
||||
^ me init
|
||||
]
|
||||
init [ cache := Set new. negativeCache := Set new. ]
|
||||
|
||||
hasSad: aNum [
|
||||
^ (negativeCache includes: (self recycle: aNum))
|
||||
]
|
||||
hasHappy: aNum [
|
||||
^ (cache includes: (self recycle: aNum))
|
||||
]
|
||||
addHappy: aNum [
|
||||
cache add: (self recycle: aNum)
|
||||
]
|
||||
addSad: aNum [
|
||||
negativeCache add: (self recycle: aNum)
|
||||
]
|
||||
|
||||
recycle: aNum [ |r n| r := Bag new.
|
||||
n := aNum.
|
||||
[ n > 0 ]
|
||||
whileTrue: [ |d|
|
||||
d := n rem: 10.
|
||||
r add: d.
|
||||
n := n // 10.
|
||||
].
|
||||
^r
|
||||
]
|
||||
|
||||
isHappy: aNumber [ |cycle number newnumber|
|
||||
number := aNumber.
|
||||
cycle := Set new.
|
||||
[ (number ~= 1) & ( (cycle includes: number) not ) ]
|
||||
whileTrue: [
|
||||
(self hasHappy: number)
|
||||
ifTrue: [ ^true ]
|
||||
ifFalse: [
|
||||
(self hasSad: number) ifTrue: [ ^false ].
|
||||
cycle add: number.
|
||||
newnumber := 0.
|
||||
[ number > 0 ]
|
||||
whileTrue: [ |digit|
|
||||
digit := number rem: 10.
|
||||
newnumber := newnumber + (digit * digit).
|
||||
number := (number - digit) // 10.
|
||||
].
|
||||
number := newnumber.
|
||||
]
|
||||
].
|
||||
(number = 1)
|
||||
ifTrue: [
|
||||
cycle do: [ :e | self addHappy: e ].
|
||||
^true
|
||||
]
|
||||
ifFalse: [
|
||||
cycle do: [ :e | self addSad: e ].
|
||||
^false
|
||||
]
|
||||
]
|
||||
].
|
||||
7
Task/Happy-numbers/Smalltalk/happy-numbers-2.st
Normal file
7
Task/Happy-numbers/Smalltalk/happy-numbers-2.st
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
|happy|
|
||||
happy := HappyNumber new.
|
||||
|
||||
1 to: 31 do: [ :i |
|
||||
(happy isHappy: i)
|
||||
ifTrue: [ i displayNl ]
|
||||
].
|
||||
25
Task/Happy-numbers/Smalltalk/happy-numbers-3.st
Normal file
25
Task/Happy-numbers/Smalltalk/happy-numbers-3.st
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
|next isHappy happyNumbers|
|
||||
|
||||
next :=
|
||||
[:n |
|
||||
(n printString collect:[:ch | ch digitValue squared] as:Array) sum
|
||||
].
|
||||
|
||||
isHappy :=
|
||||
[:n | | t already |
|
||||
already := Set new.
|
||||
t := n.
|
||||
[ t == 1 or:[ (already includes:t)]] whileFalse:[
|
||||
already add:t.
|
||||
t := next value:t.
|
||||
].
|
||||
t == 1
|
||||
].
|
||||
|
||||
happyNumbers := OrderedCollection new.
|
||||
try := 1.
|
||||
[happyNumbers size < 8] whileTrue:[
|
||||
(isHappy value:try) ifTrue:[ happyNumbers add:try].
|
||||
try := try + 1
|
||||
].
|
||||
happyNumbers printCR
|
||||
16
Task/Happy-numbers/Tcl/happy-numbers.tcl
Normal file
16
Task/Happy-numbers/Tcl/happy-numbers.tcl
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
proc is_happy n {
|
||||
set seen [list]
|
||||
while {$n > 1 && [lsearch -exact $seen $n] == -1} {
|
||||
lappend seen $n
|
||||
set n [sum_of_squares [split $n ""]]
|
||||
}
|
||||
return [expr {$n == 1}]
|
||||
}
|
||||
|
||||
set happy [list]
|
||||
set n -1
|
||||
while {[llength $happy] < 8} {
|
||||
if {[is_happy $n]} {lappend happy $n}
|
||||
incr n
|
||||
}
|
||||
puts "the first 8 happy numbers are: [list $happy]"
|
||||
Loading…
Add table
Add a link
Reference in a new issue