Happy numbers: Difference between revisions
Content added Content deleted
(Added Easylang) |
m (→{{header|Julia}}: update for Julia versions > 0.7) |
||
Line 3,972: | Line 3,972: | ||
<syntaxhighlight lang="julia"> |
<syntaxhighlight lang="julia"> |
||
function happy(x) |
function happy(x) |
||
happy_ints = |
happy_ints = Int[] |
||
int_try = 1 |
int_try = 1 |
||
while length(happy_ints) < x |
while length(happy_ints) < x |
||
n = int_try |
n = int_try |
||
past = |
past = Int[] |
||
while n != 1 |
while n != 1 |
||
n = sum(y^2 for y in digits(n)) |
|||
n in past && break |
|||
push!(past, n) |
|||
end |
|||
n == 1 && push!(happy_ints,int_try) |
n == 1 && push!(happy_ints,int_try) |
||
int_try += 1 |
int_try += 1 |
||
Line 4,000: | Line 4,001: | ||
<syntaxhighlight lang="julia">sumhappy(n) = sum(x->x^2, digits(n)) |
<syntaxhighlight lang="julia">sumhappy(n) = sum(x->x^2, digits(n)) |
||
function ishappy(x, mem = []) |
function ishappy(x, mem = Int[]) |
||
x == 1? true : |
x == 1 ? true : |
||
x in mem? false : |
x in mem ? false : |
||
ishappy(sumhappy(x),[mem ; x]) |
ishappy(sumhappy(x), [mem ; x]) |
||
end |
end |
||
nexthappy |
nexthappy(x) = ishappy(x+1) ? x+1 : nexthappy(x+1) |
||
⚫ | |||
⚫ | |||
</syntaxhighlight> |
</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 4,018: | Line 4,018: | ||
{{trans|C}} |
{{trans|C}} |
||
<syntaxhighlight lang="julia">const CACHE = 256 |
<syntaxhighlight lang="julia">const CACHE = 256 |
||
buf = zeros(Int,CACHE) |
buf = zeros(Int, CACHE) |
||
buf[ |
buf[begin] = 1 |
||
#happy(n) returns 1 if happy, 0 if not |
|||
function happy(n) |
function happy(n) |
||
if n < CACHE |
if n < CACHE |
||
Line 4,026: | Line 4,026: | ||
buf[n] = 2 |
buf[n] = 2 |
||
end |
end |
||
sqsum = 0 |
|||
nn = n |
nn = n |
||
while nn != 0 |
while nn != 0 |
||
x = nn |
nn, x = divrem(nn, 10) |
||
sqsum += x * x |
|||
nn = int8(nn/10) |
|||
end |
end |
||
x = happy( |
x = happy(sqsum) |
||
n < CACHE && (buf[n] = 2-x) |
n < CACHE && (buf[n] = 2 - x) |
||
return x |
return x |
||
end |
end |
||
function main() |
function main() |
||
i = 1 |
i, counter = 1, 1000000 |
||
while counter > 0 |
while counter > 0 |
||
if happy(i) |
if happy(i) != 0 |
||
counter -= 1 |
counter -= 1 |
||
end |
end |
||
i += 1 |
i += 1 |
||
end |
end |
||
return i-1 |
return i - 1 |
||
end |
|||
</syntaxhighlight> |
|||
=={{header|K}}== |
=={{header|K}}== |