Happy numbers: Difference between revisions

→‎{{header|C sharp|C#}}: Added cacheless, possibly higher performace version
m (→‎{{header|Haskell}}: Added type signatures, replaced top level if then else with a guard expression)
(→‎{{header|C sharp|C#}}: Added cacheless, possibly higher performace version)
Line 1,159:
First 8 happy numbers : 1,7,10,13,19,23,28,31
</pre>
 
===Alternate (cacheless)===
Instead of caching and checking for being stuck in a loop, one can terminate on the "unhappy" endpoint of 89. One might be temped to try caching the so-far-found happy and unhappy numbers and checking the cache to speed things up. However, I have found that the cache implementation overhead reduces performance compared to this cacheless version.<br/>
Reaching 10 million, the <34 second computation time was from Tio.run. It takes under 5 seconds on a somewhat modern CPU. If you edit it to max out at 100 million, it takes about 50 seconds (on the somewhat modern CPU).<lang csharp>using System;
using System.Collections.Generic;
class Program
{
 
static int[] sq = { 1, 4, 9, 16, 25, 36, 49, 64, 81 };
 
static bool isOne(int x)
{
while (true)
{
if (x == 89) return false;
int s = 0, t;
do if ((t = (x % 10) - 1) >= 0) s += sq[t]; while ((x /= 10) > 0);
if (s == 1) return true;
x = s;
}
}
 
static void Main(string[] args)
{
const int Max = 10_000_000; DateTime st = DateTime.Now;
Console.Write("---Happy Numbers---\nThe first 8:");
int c = 0, i; for (i = 1; c < 8; i++)
if (isOne(i)) Console.Write("{0} {1}", c == 0 ? "" : ",", i, ++c);
for (int m = 10; m <= Max; m *= 10)
{
Console.Write("\nThe {0:n0}th: ", m);
for (; c < m; i++) if (isOne(i)) c++;
Console.Write("{0:n0}", i - 1);
}
Console.WriteLine("\nComputation time {0} seconds.", (DateTime.Now - st).TotalSeconds);
}
}</lang>
<pre>---Happy Numbers---
The first 8: 1, 7, 10, 13, 19, 23, 28, 31
The 10th: 44
The 100th: 694
The 1,000th: 6,899
The 10,000th: 67,169
The 100,000th: 692,961
The 1,000,000th: 7,105,849
The 10,000,000th: 71,313,350
Computation time 33.264518 seconds.</pre>
 
=={{header|Clojure}}==