Iterated digits squaring: Difference between revisions

From Rosetta Code
Content added Content deleted
(First draft of the task)
 
(+ D entry)
Line 16: Line 16:


This problem derives from the [https://projecteuler.net/problem=92 Project Euler problem 92].
This problem derives from the [https://projecteuler.net/problem=92 Project Euler problem 92].

=={{header|D}}==
This is a fast imperative brute-force solution.
<lang d>void main() nothrow @nogc {
import core.stdc.stdio: printf;

enum uint magic = 89;
enum uint limit = 100_000_000;
uint[(9 ^^ 2) * 8 + 1] lookup = void;

uint[10] squares;
foreach (immutable i, ref x; squares)
x = i ^^ 2;

foreach (immutable uint i; 1 .. lookup.length) {
uint x = i;

while (x != magic && x != 1) {
uint total = 0;
while (x) {
total += squares[(x % 10)];
x /= 10;
}
x = total;
}

lookup[i] = x == magic;
}

uint magicCount = 0;
foreach (immutable uint i; 1 .. limit) {
uint x = i;
uint total = 0;

while (x) {
total += squares[(x % 10)];
x /= 10;
}

magicCount += lookup[total];
}

printf("%u\n", magicCount);
}</lang>
{{out}}
<pre>85744333</pre>

Revision as of 18:13, 23 August 2014

Iterated digits squaring is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:

15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1

An example in Python:

<lang python>>>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]</lang>

Your task is to count how many number chains in [1, 100_000_000) end with a value 89.

This problem derives from the Project Euler problem 92.

D

This is a fast imperative brute-force solution. <lang d>void main() nothrow @nogc {

   import core.stdc.stdio: printf;
   enum uint magic = 89;
   enum uint limit = 100_000_000;
   uint[(9 ^^ 2) * 8 + 1] lookup = void;
   uint[10] squares;
   foreach (immutable i, ref x; squares)
       x = i ^^ 2;
   foreach (immutable uint i; 1 .. lookup.length) {
       uint x = i;
       while (x != magic && x != 1) {
           uint total = 0;
           while (x) {
               total += squares[(x % 10)];
               x /= 10;
           }
           x = total;
       }
       lookup[i] = x == magic;
   }
   uint magicCount = 0;
   foreach (immutable uint i; 1 .. limit) {
       uint x = i;
       uint total = 0;
       while (x) {
           total += squares[(x % 10)];
           x /= 10;
       }
       magicCount += lookup[total];
   }
   printf("%u\n", magicCount);

}</lang>

Output:
85744333