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 = ref(Int)
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 = ref(Int)
past = Int[]
while n != 1
while n != 1
n = sum([y^2 for y in digits(n)])
n = sum(y^2 for y in digits(n))
contains(past,n) ? break : push!(past,n)
n in past && break
push!(past, n)
end
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 (x) = ishappy(x+1) ? x+1 : nexthappy(x+1)
nexthappy(x) = ishappy(x+1) ? x+1 : nexthappy(x+1)
happy(n) = accumulate((a, b) -> nexthappy(a), 1:n)

happy(n) = [z = 1 ; [z = nexthappy(z) for i = 1:n-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[1] = 1
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
sum = 0
sqsum = 0
nn = n
nn = n
while nn != 0
while nn != 0
x = nn%10
nn, x = divrem(nn, 10)
sum += x*x
sqsum += x * x
nn = int8(nn/10)
end
end
x = happy(sum)
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; counter = 1000000
i, counter = 1, 1000000
while counter > 0
while counter > 0
if happy(i) == 1
if happy(i) != 0
counter -= 1
counter -= 1
end
end
i += 1
i += 1
end
end
return i-1
return i - 1
end
end</syntaxhighlight>
</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==