Iterated digits squaring

From Rosetta Code
Task
Iterated digits squaring
You are encouraged to solve this task according to the task description, using any language you may know.

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:

>>> 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]
Task
Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.

Or, for much less credit - (showing that your algorithm and/or language is slow):

Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.

This problem derives from the Project Euler problem 92.

For a quick algorithm for this task see the talk page

Cf



ALGOL 68[edit]

Brute-force with some caching.

# count the how many numbers up to 100 000 000 have squared digit sums of 89            #
 
# compute a table of the sum of the squared digits of the numbers 00 to 99 #
[ 0 : 99 ]INT digit pair square sum;
FOR d1 FROM 0 TO 9 DO
FOR d2 FROM 0 TO 9 DO
digit pair square sum[ ( d1 * 10 ) + d2 ] := ( d1 * d1 ) + ( d2 * d2 )
OD
OD;
 
# returns the sum of the squared digits of n #
PROC squared digit sum = ( INT n )INT:
BEGIN
INT result := 0;
INT rest := n;
WHILE rest /= 0 DO
INT digit pair = rest MOD 100;
result PLUSAB digit pair square sum[ digit pair ];
rest OVERAB 100
OD;
result
END # squared digit sum # ;
 
# for values up to 100 000 000, the largest squred digit sum will be that of 99 999 999 #
# i.e. 81 * 8 = 648, we will cache the values of the squared digit sums #
INT cache max = 81 * 8;
[ 1 : cache max ]INT cache;
FOR i TO cache max DO cache[ i ] := 0 OD;
 
INT count 89 := 0;
 
# fill in the cache #
FOR value FROM 2 TO cache max DO cache[ value ] := squared digit sum( value ) OD;
# we "know" that 89 and 1 are the terminal values #
cache[ 1 ] := 1;
cache[ 89 ] := 89;
FOR value FROM 2 TO cache max DO
INT sum := cache[ value ];
WHILE sum /= 1 AND sum /= 89 DO
sum := cache[ sum ]
OD;
cache[ value ] := sum
OD;
 
FOR value FROM 1 TO 100 000 000 DO
IF cache[ squared digit sum( value ) ] = 89 THEN count 89 +:= 1 FI
OD;
 
print( ( "Number of values whose squared digit sum is 89: ", whole( count 89, -10 ), newline ) )
Output:
Number of values whose squared digit sum is 89:   85744333

BBC BASIC[edit]

Three versions timed on a 2.50GHz Intel Desktop.

      REM Version 1: Brute force
REM ---------------------------------------------------------
T%=TIME
N%=0
FOR I%=1 TO 100000000
J%=I%
REPEAT
K%=0:REPEAT K%+=(J%MOD10)^2:J%=J%DIV10:UNTIL J%=0
J%=K%
UNTIL J%=89 OR J%=1
IF J%>1 N%+=1
NEXT
PRINT "Version 1: ";N% " in ";(TIME-T%)/100 " seconds."
 
REM Version 2: Brute force + building lookup table
REM ---------------------------------------------------------
T%=TIME
DIM B% 9*9*8,H%(9)
N%=0
FOR I%=1 TO 100000000
J%=I%
H%=0
REPEAT
K%=0:REPEAT K%+=(J%MOD10)^2:J%=J%DIV10:UNTIL J%=0
H%(H%)=K%:H%+=1
J%=K%
IF B%?J%=1 EXIT REPEAT
UNTIL J%=89 OR J%=1
IF J%>1 N%+=1:WHILE H%>0:H%-=1:B%?H%(H%)=1:ENDWHILE
NEXT
PRINT "Version 2: ";N% " in ";(TIME-T%)/100 " seconds."
 
REM Version 3: Calc possible combinations (translation of C)
REM ---------------------------------------------------------
T%=TIME
DIM B%(9*9*8):B%(0)=1
FOR N%=1 TO 8
FOR I%=9*9*N% TO 1 STEP -1
FOR J%=1 TO 9
S%=J%*J%
IF S%>I% EXIT FOR
B%(I%)+=B%(I%-S%)
NEXT
NEXT
NEXT
 
N%=0
FOR I%=1 TO 9*9*8
J%=I%
REPEAT
K%=0:REPEAT K%+=(J%MOD10)^2:J%=J%DIV10:UNTIL J%=0
J%=K%
UNTIL J%=89 OR J%=1
IF J%>1 N%+=B%(I%)
NEXT
PRINT "Version 3: ";N% " in ";(TIME-T%)/100 " seconds."
 
END
Output:
Version 1: 85744333 in 1447.08 seconds.
Version 2: 85744333 in 718.04 seconds.
Version 3: 85744333 in 0.02 seconds.

C[edit]

C99, tested with "gcc -std=c99". Record how many digit square sum combinations there are. This reduces numbers to , and the complexity is about . The 64 bit integer counter is good for up to , which takes practically no time to run.

#include <stdio.h>
 
typedef unsigned long long ull;
 
int is89(int x)
{
while (1) {
int s = 0;
do s += (x%10)*(x%10); while ((x /= 10));
 
if (s == 89) return 1;
if (s == 1) return 0;
x = s;
}
}
 
 
int main(void)
{
// array bounds is sort of random here, it's big enough for 64bit unsigned.
ull sums[32*81 + 1] = {1, 0};
 
for (int n = 1; ; n++) {
for (int i = n*81; i; i--) {
for (int j = 1; j < 10; j++) {
int s = j*j;
if (s > i) break;
sums[i] += sums[i-s];
}
}
 
ull count89 = 0;
for (int i = 1; i < n*81 + 1; i++) {
if (!is89(i)) continue;
 
if (sums[i] > ~0ULL - count89) {
printf("counter overflow for 10^%d\n", n);
return 0;
}
count89 += sums[i];
}
 
printf("1->10^%d: %llu\n", n, count89);
}
 
return 0;
}
Output:
1->10^1: 7
1->10^2: 80
1->10^3: 857
1->10^4: 8558
1->10^5: 85623
1->10^6: 856929
1->10^7: 8581146
1->10^8: 85744333
1->10^9: 854325192
1->10^10: 8507390852
1->10^11: 84908800643
1->10^12: 850878696414
1->10^13: 8556721999130
1->10^14: 86229146720315
1->10^15: 869339034137667
1->10^16: 8754780882739336
1->10^17: 87975303595231975
1->10^18: 881773944919974509
1->10^19: 8816770037940618762
counter overflow for 10^20

Fast C implementation (<1 second my machine), which performs iterated digits squaring only once for each unique 8 digit combination. The cases 0 and 100,000,000 are ignored since they don't sum to 89:

 
#include <stdio.h>
 
const int digits[] = { 0,1,2,3,4,5,6,7,8,9 };
 
// calculates factorial of a number
int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
 
// returns sum of squares of digits of n
unsigned int sum_square_digits(unsigned int n) {
int i,num=n,sum=0;
// process digits one at a time until there are none left
while (num > 0) {
// peal off the last digit from the number
int digit=num % 10;
num=(num - digit)/10;
// add it's square to the sum
sum=sum+digit*digit;
}
return sum;
}
 
// builds all combinations digits 0-9 of length len
// for each of these it will perform iterated digit squaring
// and for those which result in 89 add to a counter which is
// passed by pointer.
long choose_sum_and_count_89(int * got, int n_chosen, int len, int at, int max_types, int *count89)
{
int i;
long count = 0;
int digitcounts[10];
for (i=0; i < 10; i++) {
digitcounts[i]=0;
}
if (n_chosen == len) {
if (!got) return 1;
 
int sum=0;
for (i = 0; i < len; i++) {
int digit=digits[got[i]];
digitcounts[digit]++;
sum=sum + digit * digit;
}
if (sum == 0) {
return 1;
}
if ((sum != 1) && (sum != 89)) {
while ((sum != 1) && (sum != 89)) {
sum=sum_square_digits(sum);
}
}
if (sum == 89) {
int count_this_comb=factorial(len);
for (i=0; i<10; i++) {
count_this_comb/=factorial(digitcounts[i]);
}
(*count89)+=count_this_comb;
}
 
return 1;
}
 
for (i = at; i < max_types; i++) {
if (got) got[n_chosen] = i;
count += choose_sum_and_count_89(got, n_chosen + 1, len, i, max_types, count89);
}
return count;
}
 
int main(void)
{
int chosen[10];
int count=0;
// build all unique 8 digit combinations which represent
// numbers 0-99,999,999 and count those
// whose iterated digit squaring sum to 89
// case 0, 100,000,000 are ignored since they don't sum to 89
choose_sum_and_count_89(chosen, 0, 8, 0, 10, &count);
printf("%d\n",count);
return 0;
}
 
Output:
85744333

C++[edit]

Slow (~10 seconds on my machine) brute force C++ implementation:

 
#include <iostream>
 
// returns sum of squares of digits of n
unsigned int sum_square_digits(unsigned int n) {
int i,num=n,sum=0;
// process digits one at a time until there are none left
while (num > 0) {
// peal off the last digit from the number
int digit=num % 10;
num=(num - digit)/10;
// add it's square to the sum
sum+=digit*digit;
}
return sum;
}
int main(void) {
unsigned int i=0,result=0, count=0;
for (i=1; i<=100000000; i++) {
// if not 1 or 89, start the iteration
if ((i != 1) || (i != 89)) {
result = sum_square_digits(i);
}
// otherwise we're done already
else {
result = i;
}
// while we haven't reached 1 or 89, keep iterating
while ((result != 1) && (result != 89)) {
result = sum_square_digits(result);
}
if (result == 89) {
count++;
}
}
std::cout << count << std::endl;
return 0;
}
 
Output:
85744333

Ceylon[edit]

shared void run() {
 
function digitsSquaredSum(variable Integer n) {
variable value total = 0;
while(n > 0) {
total += (n % 10) ^ 2;
n /= 10;
}
return total;
}
 
function lastSum(variable Integer n) {
while(true) {
n = digitsSquaredSum(n);
if(n == 89 || n == 1) {
return n;
}
}
}
 
variable value eightyNines = 0;
for(i in 1..100M - 1) {
if(lastSum(i) == 89) {
eightyNines++;
}
}
print(eightyNines);
}

Clojure[edit]

Direct Method[edit]

(ns async-example.core
(:require [clojure.math.numeric-tower :as math])
(:use [criterium.core])
(:gen-class))
(defn sum-sqr [digits]
" Square sum of list of digits "
(let [digits-sqr (fn [n]
(apply + (map #(* % %) digits)))]
(digits-sqr digits)))
 
(defn get-digits [n]
" Converts a digit to a list of digits (e.g. 545 -> ((5) (4) (5)) (used for squaring digits) "
(map #(Integer/valueOf (str %)) (String/valueOf n)))
 
(defn -isNot89 [x]
" Returns nil on 89 "
(cond
(= x 0) 0
(= x 89) nil
(= x 1) 0
(< x 10) (recur (* x x))
:else (recur (sum-sqr (get-digits x)))))
 
;; Cached version of isNot89 (i.e. remembers prevents inputs, and returns result by looking it up when input repeated)
(def isNot89 (memoize -isNot89))
 
(defn direct-method [ndigits]
" Simple approach of looping through all the numbers from 0 to 10^ndigits - 1 "
(->>
(math/expt 10 ndigits)
(range 0) ; 0 to 10^ndigits
(filter #(isNot89 (sum-sqr (get-digits %)))) ; filters out 89
(count) ; count non-89
(- (math/expt 10 ndigits)))) ; count 89 (10^ndigits - (count 89))
 
 
(time (println (direct-method 8)))
 
Output:
85744333
Time: 335 seconds

Using Combinations[edit]

 
(def DIGITS (range 0 10))
 
(defn -factorial [n]
(apply * (take n (iterate inc 1))))
; Cached version of factorial
(def factorial (memoize -factorial))
 
(defn -combinations [coll k]
" From http://rosettacode.org/wiki/Combinations_with_repetitions#Clojure "
(when-let [[x & xs] coll]
(if (= k 1)
(map list coll)
(concat (map (partial cons x) (-combinations coll (dec k)))
(-combinations xs k)))))
; Cached version of combinations
(def combinations (memoize -combinations))
 
(defn comb [n r]
" count of n items select r "
(/ (/ (factorial n) (factorial r)) (factorial (- n r))))
 
(defn count-digits [digit-list]
" count nunmber of occurences of digit in list "
(reduce (fn [m v] (update-in m [v] (fnil inc 0))) {} digit-list))
 
(defn count-patterns [c]
" Count of number of patterns with these digits "
(->>
c
(count-digits)
(reduce (fn [accum [k v]]
(* accum (factorial v)))
1)
(/ (factorial (count c)))))
 
(defn itertools-comb [ndigits]
(->>
ndigits
(combinations DIGITS)
(filter #(is89 (sum-sqr %)))  ; items which are not 89 (i.e. 1 since lower count)
(reduce (fn [acc c]
(+ acc (count-patterns c)))
0)
(- (math/expt 10 ndigits))))
 
(println (itertools-comb 8))
;; Time obtained using benchmark library (i.e. (bench (itertools-comb 8)) )
 
{
Output:
85744333
Time: 78 ms  (i.e. using combinations was over 4,000 times faster
                   both tested on i7 CPU [email protected])

Common Lisp[edit]

 
(defun square (number)
(expt number 2))
 
(defun list-digits (number)
"Return the `number' as a list of its digits."
(loop
:for (rest digit) := (multiple-value-list (truncate number 10))
:then (multiple-value-list (truncate rest 10))
:collect digit
:until (zerop rest)))
 
(defun next (number)
(loop
:for digit :in (list-digits number)
:sum (square digit)))
 
(defun chain-end (number)
"Return the ending number after summing the squaring of the digits of
`number'. Either 1 or 89."

(loop
:for next := (next number) :then (next next)
:until (or (eql next 1)
(eql next 89))
:finally (return next)))
 
(time
(loop
:with count := 0
:for candidate :from 1 :upto 100000000
:do (when (eql 89 (chain-end candidate))
(incf count))
:finally (return count)))
 
Output:
Evaluation took:
  1128.773 seconds of real time
  1126.231095 seconds of total run time (1117.296987 user, 8.934108 system)
  [ Run times consist of 56.419 seconds GC time, and 1069.813 seconds non-GC time. ]
  99.77% CPU
  2,815,545,509,836 processor cycles
  580,663,356,272 bytes consed

*

D[edit]

A simple memoizing partially-imperative brute-force solution:

import std.stdio, std.algorithm, std.range, std.functional;
 
uint step(uint x) pure nothrow @safe @nogc {
uint total = 0;
while (x) {
total += (x % 10) ^^ 2;
x /= 10;
}
return total;
}
 
uint iterate(in uint x) nothrow @safe {
return (x == 89 || x == 1) ? x : x.step.memoize!iterate;
}
 
void main() {
iota(1, 100_000_000).filter!(x => x.iterate == 89).count.writeln;
}
Output:
85744333

The run-time is about 10 seconds compiled with ldc2.

A fast imperative brute-force solution:

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);
}

The output is the same. The run-time is less than 3 seconds compiled with ldc2.

A more efficient solution:

import core.stdc.stdio, std.algorithm, std.range;
 
enum factorial = (in uint n) pure nothrow @safe @nogc
=> reduce!q{a * b}(1u, iota(1u, n + 1));
 
uint iLog10(in uint x) pure nothrow @safe @nogc
in {
assert(x > 0);
} body {
return (x >= 1_000_000_000) ? 9 :
(x >= 100_000_000) ? 8 :
(x >= 10_000_000) ? 7 :
(x >= 1_000_000) ? 6 :
(x >= 100_000) ? 5 :
(x >= 10_000) ? 4 :
(x >= 1_000) ? 3 :
(x >= 100) ? 2 :
(x >= 10) ? 1 : 0;
}
 
uint nextStep(uint x) pure nothrow @safe @nogc {
typeof(return) result = 0;
 
while (x > 0) {
result += (x % 10) ^^ 2;
x /= 10;
}
return result;
}
 
uint check(in uint[] number) pure nothrow @safe @nogc {
uint candidate = reduce!((tot, n) => tot * 10 + n)(0, number);
 
while (candidate != 89 && candidate != 1)
candidate = candidate.nextStep;
 
if (candidate == 89) {
uint[10] digitsCount;
foreach (immutable d; number)
digitsCount[d]++;
 
return reduce!((r, c) => r / c.factorial)
(number.length.factorial, digitsCount);
}
 
return 0;
}
 
void main() nothrow @nogc {
enum uint limit = 100_000_000;
immutable uint cacheSize = limit.iLog10;
 
uint[cacheSize] number;
uint result = 0;
uint i = cacheSize - 1;
 
while (true) {
if (i == 0 && number[i] == 9)
break;
if (i == cacheSize - 1 && number[i] < 9) {
number[i]++;
result += number.check;
} else if (number[i] == 9) {
i--;
} else {
number[i]++;
number[i + 1 .. $] = number[i];
i = cacheSize - 1;
result += number.check;
}
}
 
printf("%u\n", result);
}

The output is the same. The run-time is about 0.04 seconds or less. This third version was ported to D and improved from: mathblog.dk/project-euler-92-square-digits-number-chain/

A purely functional version, from the Haskell code. It includes two functions currently missing in Phobos used in the Haskell code.

Translation of: Haskell
import std.stdio, std.typecons, std.traits, std.typetuple, std.range, std.algorithm;
 
auto divMod(T)(T x, T y) pure nothrow @safe @nogc {
return tuple(x / y, x % y);
}
 
auto expand(alias F, B)(B x) pure nothrow @safe @nogc
if (isCallable!F &&
is(ParameterTypeTuple!F == TypeTuple!B)
&& __traits(isSame, TemplateOf!(ReturnType!F), Nullable)
&& isTuple!(TemplateArgsOf!(ReturnType!F)[0])
&& is(TemplateArgsOf!(TemplateArgsOf!(ReturnType!F)[0])[1] == B)) {
 
alias NAB = ReturnType!F;
alias AB = TemplateArgsOf!NAB[0];
alias A = AB.Types[0];
 
struct Expand {
bool first;
NAB last;
 
@property bool empty() pure nothrow @safe @nogc {
if (first) {
first = false;
popFront;
}
return last.isNull;
}
 
@property A front() pure nothrow @safe @nogc {
if (first) {
first = false;
popFront;
}
return last.get[0];
}
 
void popFront() pure nothrow @safe @nogc { last = F(last.get[1]); }
}
 
return Expand(true, NAB(AB(A.init, x)));
}
 
//------------------------------------------------
 
uint step(uint x) pure nothrow @safe @nogc {
Nullable!(Tuple!(uint, uint)) f(uint n) pure nothrow @safe @nogc {
return (n == 0) ? typeof(return)() : typeof(return)(divMod(n, 10u).reverse);
}
 
return expand!f(x).map!(x => x ^^ 2).sum;
}
 
uint iter(uint x) pure nothrow @nogc {
return x.recurrence!((a, n) => step(a[n - 1])).filter!(y => y.among!(1, 89)).front;
}
 
void main() {
iota(1u, 100_000u).filter!(n => n.iter == 89).count.writeln;
}

With a small back-porting (to run it with the Phobos of LDC2 2.065) it runs in about 15.5 seconds.

ERRE[edit]

 
PROGRAM ITERATION
 
BEGIN
PRINT(CHR$(12);) ! CLS
INPUT(N)
LOOP
N$=MID$(STR$(N),2)
S=0
FOR I=1 TO LEN(N$) DO
A=VAL(MID$(N$,I,1))
S=S+A*A
END FOR
IF S=89 OR S=1 THEN PRINT(S;) EXIT END IF
PRINT(S;)
N=S
END LOOP
PRINT
END PROGRAM
 

This program verifies a number only. With a FOR..END FOR loop it's possible to verify a number range.

FreeBASIC[edit]

' FB 1.05.0 Win64
 
' similar to C Language (first approach)
' timing for i3 @ 2.13 GHz
 
Function endsWith89(n As Integer) As Boolean
Dim As Integer digit, sum = 0
Do
While n > 0
digit = n Mod 10
sum += digit * digit
n \= 10
Wend
If sum = 89 Then Return True
If sum = 1 Then Return False
n = sum
sum = 0
Loop
End Function
 
Dim As Double start = timer
Dim sums(0 To 8 * 81) As UInteger
sums(0) = 1
sums(1) = 0
Dim s As Integer
For n As Integer = 1 To 8
For i As Integer = n * 81 To 1 Step -1
For j As Integer = 1 To 9
s = j * j
If s > i Then Exit For
sums(i) += sums(i - s)
Next j
Next i
 
If n = 8 Then
Dim As UInteger count89 = 0
For i As Integer = 1 To n * 81
If Not endsWith89(i) Then Continue For
count89 += sums(i)
Next i
Print "There are";count89; " numbers from 1 to 100 million ending with 89"
End If
Next
Print "Elapsed milliseconds ="; Int((timer - start) * 1000 + 0.5)
Print
Print "Press any key to quit"
Sleep
Output:
There are 85744333 numbers from 1 to 100 million ending with 89
Elapsed milliseconds = 2

Frink[edit]

 
total = 0
d = new dict
var sum
 
for n = 1 to 100 million - 1
{
sum = n
do
{
if sum < 1000 and [email protected] != undef
{
sum = [email protected]
break
}
 
c = sum
 
sum = 0
for digit = integerDigits[c]
sum = sum + digit^2
} while (sum != 89) and (sum != 1)
 
if (n < 1000)
[email protected] = sum
 
if (sum == 89)
total = total + 1
}
 
println[total]
 
Output:
85744333

Go[edit]

It's basic. Runs in about 30 seconds on an old laptop.

package main
 
import (
"fmt"
)
 
func main() {
var d, n, o, u, u89 int64
 
for n = 1; n < 100000000; n++ {
o = n
for {
u = 0
for {
d = o%10
o = (o - d) / 10
u += d*d
if o == 0 {
break
}
}
if u == 89 || u == 1 {
if u == 89 { u89++ }
break
}
o = u
}
}
fmt.Println(u89)
}
Output:
85744333

Haskell[edit]

Basic solution that contains just a little more than the essence of this computation. This runs in less than eight minutes:

import Data.List (unfoldr)
import Data.Tuple (swap)
 
step :: Int -> Int
step = sum . map (^ 2) . unfoldr f where
f 0 = Nothing
f n = Just . swap $ n `divMod` 10
 
iter :: Int -> Int
iter = head . filter (`elem` [1, 89]) . iterate step
 
main = do
print $ length $ filter ((== 89) . iter) [1 .. 99999999]
Output:
85744333

J[edit]

Here's an expression to turn a number into digits:

digits=: 10&#.inv

And here's an expression to square them and find their sum:

sumdigsq=: +/"1@:*:@digits

But note that while the task description claims "you always end with either 1 or 89", that claim is somewhat arbitrary.

But only somewhat the loop is 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89, so it only ends with 1 or one of the numbers in this loop. 42 is of course far more significant and the one I would choose!!--Nigel Galloway (talk) 10:12, 16 September 2014 (UTC)
   sumdigsq^:(i.16) 15
15 26 40 16 37 58 89 145 42 20 4 16 37 58 89 145

You could just as easily claim that you always end with either 1 or 4. So here's a routine which repeats the sum-square process until the sequence converges, or until it reaches the value 4:

itdigsq4=:4 = sumdigsq^:(0=e.&4)^:_"0

But we do not actually need to iterate. The largest value after the first iteration would be:

   sumdigsq 99999999
648

So we could write a routine which works for the intended range, and stops after the first iteration:

itdigsq1=:1 = sumdigsq^:(0=e.&4)^:_"0
digsq1e8=:(I.itdigsq1 i.649) e.~ sumdigsq

In other words, if the result after the first iteration is any of the numbers in the range 0..648 which converges to 1, it's not a result which would converge to the other loop. This is considerably faster than trying to converge 1e8 sequences, and also evades having to pick an arbitrary stopping point for the sequence which loops for the bulk computation.

And this is sufficient to find our result. We don't want to compute the entire batch of values in one pass, however, so let's break this up into 100 batches of one million each:

   +/+/@:[email protected]"1(1+i.100 1e6)
85744333

Of course, there are faster ways of obtaining that result. The fastest is probably this:

   85744333
85744333

This might be thought of as representing the behavior of a highly optimized compiled program. We could abstract this further by using the previous expression at compile time, so we would not have to hard code it.

Julia[edit]

Brute-force solution, which runs in about 12 seconds on my machine:

function iterate(m)
while m != 1 && m != 89
s = 0
while m > 0 # compute sum of squares of digits
m, d = divrem(m, 10)
s += d*d
end
m = s
end
return m
end
function itercount(N)
count = 0
for n in 1:N
count += iterate(n) == 89
end
return count
end

More clever combinatorial solution that loops over all unique sets of digits (runs in < 0.01 seconds):

function itercount_combinations(ndigits)
count = 0
f = factorial(ndigits)
# loop over all combinations of ndigits decimal digits:
for c in combinations([1:(10+ndigits-1)],ndigits)
s = 0
perms = 1
prevdigit = -1
repeat = 1
for k = 1:length(c) # sum digits^2 and count permutations
digit = c[k]-k
s += digit*digit
# accumulate number of permutations of repeated digits
if digit == prevdigit
repeat += 1
perms *= repeat
else
prevdigit = digit
repeat = 1
end
end
if s > 0 && iterate(s) == 89
count += div(f, perms) # numbers we can get from digits
end
end
return count
end
Output:
julia> @time itercount(100_000_000)
elapsed time: 12.45469116 seconds (96 bytes allocated)
85744333

julia> @time itercount_combinations(8)
elapsed time: 0.007778687 seconds (6223784 bytes allocated)
85744333

julia> @time itercount_combinations(17)
elapsed time: 1.97602701 seconds (1299813368 bytes allocated, 39.95% gc time)
87975303595231975

Java[edit]

Works with: Java version 8
import java.util.stream.IntStream;
 
public class IteratedDigitsSquaring {
 
public static void main(String[] args) {
long r = IntStream.range(1, 100_000_000)
.parallel()
.filter(n -> calc(n) == 89)
.count();
System.out.println(r);
}
 
private static int calc(int n) {
while (n != 89 && n != 1) {
int total = 0;
while (n > 0) {
total += Math.pow(n % 10, 2);
n /= 10;
}
n = total;
}
return n;
}
}
85744333

jq[edit]

Works with: jq version 1.4

The algorithm presented here caches the results for 1 ... D*81 (where D is the relevant number of digits) and uses the combinatorial approach, but to keep things relatively brief, the factorials themselves are not cached.

Part 1: Foundations

def factorial: reduce range(2;.+1) as $i (1; . * $i);
 
# Pick n items (with replacement) from the input array,
# but only consider distinct combinations:
def pick(n):
def pick(n; m): # pick n, from m onwards
if n == 0 then []
elif m == length then empty
elif n == 1 then (.[m:][] | [.])
else ([.[m]] + pick(n-1; m)), pick(n; m+1)
end;
pick(n;0) ;
 
# Given any array, produce an array of [item, count] pairs for each run.
def runs:
reduce .[] as $item
( [];
if . == [] then [ [ $item, 1] ]
else .[length-1] as $last
| if $last[0] == $item then (.[0:length-1] + [ [$item, $last[1] + 1] ] )
else . + [[$item, 1]]
end
end ) ;

Part 2: The Generic Task

Count how many number chains beginning with n (where 0 < n < 10^D) end with a value 89.

def terminus:
# sum of the squared digits
def ssdigits: tostring | explode | map(. - 48 | .*.) | add;
 
if . == 1 or . == 89 then .
else ssdigits | terminus
end;
 
# Count the number of integers i in [1... 10^D] with terminus equal to 89.
def task(D):
# The max sum of squares is D*81 so return an array that will instantly
# reveal whether n|terminus is 89:
def cache:
reduce range(1; D*81+1) as $d ([false]; . + [$d|terminus == 89]);
 
# Compute n / (i1! * i2! * ... ) for the given combination,
# which is assumed to be in order:
def combinations(n):
runs | map( .[1] | factorial) | reduce .[] as $i (n; ./$i);
 
cache as $cache
| (D|factorial) as $Dfactorial
| reduce ([range(0;10)] | pick(D)) as $digits
(0;
($digits | map(.*.) | add) as $ss
| if $cache[$ss] then . + ($digits|combinations($Dfactorial))
else .
end) ;

Part 3: D=8

task(8)
Output:
$ jq -M -n -f Iterated_digits_squaring_using_pick.jq
85744333
 
# Using jq>1.4:
# user 0m2.595s
# sys 0m0.010s
 
# Using jq 1.4:
# user 0m3.942s
# sys 0m0.009s

Kotlin[edit]

Translation of: FreeBASIC
// version 1.0.6
 
fun endsWith89(n: Int): Boolean {
var digit: Int
var sum = 0
var nn = n
while (true) {
while (nn > 0) {
digit = nn % 10
sum += digit * digit
nn /= 10
}
if (sum == 89) return true
if (sum == 1) return false
nn = sum
sum = 0
}
}
 
fun main(args: Array<String>) {
val sums = IntArray(8 * 81 + 1)
sums[0] = 1
sums[1] = 0
var s: Int
for (n in 1 .. 8)
for (i in n * 81 downTo 1)
for (j in 1 .. 9) {
s = j * j
if (s > i) break
sums[i] += sums[i - s]
}
var count89 = 0
for (i in 1 .. 8 * 81)
if (endsWith89(i)) count89 += sums[i]
println("There are $count89 numbers from 1 to 100 million ending with 89")
}
Output:
There are 85744333 numbers from 1 to 100 million ending with 89

Lua[edit]

squares = {}
 
for i = 0, 9 do
for j = 0, 9 do
squares[i * 10 + j] = i * i + j * j
end
end
 
for i = 1, 99 do
for j = 0, 99 do
squares[i * 100 + j] = squares[i] + squares[j]
end
end
 
function sum_squares(n)
if n < 9999.5 then
return squares[n]
else
local m = math.floor(n / 10000)
return squares[n - 10000 * m] + sum_squares(m)
end
end
 
memory = {}
 
function calc_1_or_89(n)
local m = {}
n = memory[n] or n
while n ~= 1 and n ~= 89 do
n = memory[n] or sum_squares(n)
table.insert(m, n)
end
for _, i in pairs(m) do
memory[i] = n
end
return n
end
 
counter = 0
 
for i = 1, 100000000 do
if calc_1_or_89(i) == 89 then
counter = counter + 1
end
end
 
print(counter)
Output:
85744333

Mathematica / Wolfram Language[edit]

sumDigitsSquared[n_Integer] := Total[IntegerDigits[n]^2]
stopValues = Join[{1}, NestList[sumDigitsSquared, 89, 7]];
iterate[n_Integer] :=
NestWhile[sumDigitsSquared, n, Intersection[stopValues, {#}] == {} &]
 
numberOfDigits = 8;
maxSum = numberOfDigits 9^2;
loopVariables =
[email protected]["i" <> ToString[n], {n, numberOfDigits}];
iteratesToOne = Cases[[email protected], _?(iterate[#] == 1 &)];
allIterators =
Flatten[{[email protected]#, 9}] & /@ Partition[loopVariables, 2, 1];
maxCombinations = numberOfDigits!;
 
ssd =
SparseArray[Table[n^2 -> numberOfDigits, {n, 9}], {maxSum}];
 
Do[
variables = loopVariables[[;; digitCount]];
iterators = allIterators[[;; digitCount - 1]];
 
Do[ssd +=
SparseArray[
Total[variables^2] ->
maxCombinations/
Times @@ (Tally[PadRight[variables, numberOfDigits]][[All,
2]]!), {maxSum}], {i, 9}, Evaluate[Sequence @@ iterators]],
 
{digitCount, 2, numberOfDigits}];
 
onesCount =
Total[Cases[
ArrayRules[ssd] /.
HoldPattern[{a_} -> b_] :> {a,
b}, {_?(MemberQ[iteratesToOne, #] &), _}][[All, 2]]];
 
(10^numberOfDigits - 1) - onesCount
Output:
85744333

Oberon-2[edit]

{{works with|oo2c Version 2}

 
MODULE DigitsSquaring;
IMPORT
Out;
 
VAR
i,hits89: LONGINT;
 
PROCEDURE Squaring(n: LONGINT): LONGINT;
VAR
d, sum: LONGINT;
BEGIN
LOOP
sum := 0;
WHILE n > 0 DO
d := n MOD 10;
INC(sum,d * d);
n := n DIV 10
END;
IF (sum = 1) OR (sum = 89) THEN EXIT END;
n := sum;
END;
 
RETURN sum
END Squaring;
 
BEGIN
hits89 := 0;
FOR i := 1 TO 100000000 DO
IF Squaring(i) = 89 THEN INC(hits89) END
END;
Out.LongInt(hits89,0);Out.Ln
END DigitsSquaring.
 
 
Output:
85744333

real    0m12.201s
user    0m12.179s
sys     0m0.001s

Oforth[edit]

Brute force implementation

: sq_digits(n) 
while (n 1 <> n 89 <> and ) [
0 while(n) [ n 10 /mod ->n dup * + ]
->n
] n ;
 
: iterDigits | i | 0 100000000 loop: i [ i sq_digits 89 &= + ] . ;
Output:
85744333

PARI/GP[edit]

ssd(n)=n=digits(n); sum(i=1, #n, n[i]^2);
happy(n)=while(n>6, n=ssd(n)); n==1;
ct(n)=my(f=n!,s=10^n-1,d); forvec(v=vector(9,i,[0,n]), d=vector(9,i, if(i>8,n,v[i+1])-v[i]); if(happy(sum(i=1,9,d[i]*i^2)), s-=f/prod(i=1,9,d[i]!)/v[1]!), 1); s;
ct(8)
Output:
%1 = 85744333

Pascal[edit]

A limited, but fast implementation (up to 10e14). It calculates first all the possible sums up to cM= sqrt(MAX), with the drawback that cM must be 10^n and can only count from 10^n to 10^(2*n). Runtime: n-> 100*n => t(100*n)-> ~10*t(n) O(n) sqrt(n)

1E8 -> runtime 0..4 ms // not really measureable 
1E12-> runtime 0.22 secs
1E14 -> runtime 2,7 secs
1E16 -> runtime 31,0 secs
1E18 -> runtime  354 secs // 2GByte

Tested with freepascal.

program Euler92;
const
maxdigCnt = 14;
//2* to use the sum of two square-sums without access violation
maxPoss = 2* 9*9*maxdigCnt;// every digit is 9
cM = 10*1000*1000;// 10^(maxdigCnt div 2)
IdxSqrSum = cM;//MaxPoss;//max(cM,MaxPoss);
type
tSqrSum = array[0..IdxSqrSum] of Word;
tEndsIn = array[0..maxPoss]of Byte;
tresCache = array[0..maxPoss]of Uint64;
 
var
aSqrDigSum : tSqrSum;
aEndsIn: tEndsIn;
aresCache : tresCache;
 
procedure CreateSpuareDigitSum;
var
i,j,k,l : integer;
begin
For i := 0 to 9 do
aSqrDigSum[i] := sqr(i);
k := 10;
l := k;
while k < cM do
begin
For i := 1 to 9 do
For j := 0 to k-1 do
begin
aSqrDigSum[l]:=aSqrDigSum[i]+aSqrDigSum[j];
inc(l);
end;
k := l;
end;
aSqrDigSum[l] := 1;
end;
 
function InitEndsIn(n:LongWord):longWord;
{fill aEndsIN recursive}
var
d,s:LongWord;
begin
IF n in [0..1] then
begin
InitEndsIn := n;
EXIT;
end;
s := aSqrDigSum[n];
{if unknown}
IF aEndsIN[s] = byte(-1) then
begin
d := InitEndsIn(s);
aEndsIN[s]:= d;
InitEndsIn := d;
end
else
InitEndsIn := aEndsIN[s];
end;
 
function CntSmallOnes(s:longWord;
n:longWord=cM-1):NativeUint;
var
i: longword;
begin
result := 0;
For i := cM-1 downto 0 do
result := result+aEndsIN[aSqrDigSum[i]+s];
end;
 
procedure Init;
var
i,j,cnt : integer;
begin
CreateSpuareDigitSum;
fillchar(aEndsIN,Sizeof(aEndsIN) ,#255);
aEndsIN[0] := 0;
aEndsIN[1]:= 1;
aEndsIN[89]:= 0;// no need to use 89
For i := 1 to maxPoss do
aEndsIN[i]:= InitEndsIN(i);
 
cnt := 0;
fillchar(aresCache,SizeOf(aresCache),#0);
For i := Low(tSqrSum) to high(tSqrSum) do
begin
j := aSqrDigSum[i];
If aresCache[j] = 0 then
begin
// write(i,',');
aresCache[j] := CntSmallOnes(j);
inc(cnt);
end;
end;
// writeln; writeln(cnt,' small counts out of ',cM);
end;
{
function EndsIn(n:LongWord):Word;
var
d,s:LongWord;
begin
d := n;
s := 0;
while d > High(tSqrSum) do
begin
s := s+aSqrDigSum[d Mod cM];
d := d Div cM
end;
s :=s+aSqrDigSum[d];
EndsIn := aEndsIN[s];
end;
}

 
function CntOnes(s: longWord;n:Int64):Int64;
var
i : Int64;
begin
writeln;
result := 0;
i := n div cM;
repeat
result := result+aresCache[s+aSqrDigSum[i]];
dec(i)
until i < 0
end;
 
const
upperlimit = cM*cM ;
var
Res : Int64;
begin
Init;
Res := CntOnes(0,upperlimit-1)+1;
writeln('there are ',res,' 1s ');
writeln('there are ',upperlimit-res,' 89s ');
end.
 
output i3 3.5 Ghz

10e18 //658 small counts out of 1000000000 there are 118226055080025491 1s there are 881773944919974509 89s

real 5m54.431s user 5m53.977s

10e14 there are 13770853279685 1s there are 86229146720315 89s

real 0m2.699s user 0m2.693s

Perl[edit]

Translation of: perl6
use warnings;
use strict;
 
my @sq = map { $_ ** 2 } 0 .. 9;
my %cache;
my $cnt = 0;
 
sub Euler92 {
my $n = 0 + join( '', sort split( '', shift ) );
$cache{$n} //= ($n == 1 || $n == 89) ? $n :
Euler92( sum( @sq[ split '', $n ] ) )
}
 
sub sum {
my $sum;
$sum += shift while @_;
$sum;
}
 
for (1 .. 100_000_000) {
++$cnt if Euler92( $_ ) == 89;
}
 
print $cnt;
   85744333

Perl 6[edit]

This fairly abstract version does caching and filtering to reduce the number of values it needs to check and moves calculations out of the hot loop, but is still interminably slow... even for just up to 1,000,000.

constant @sq = ^10 X** 2;
my $cnt = 0;
 
sub Euler92($n) {
$n == any(1,89) ?? $n !!
(state %){$n} //= Euler92( [+] @sq[$n.comb] )
}
 
for 1 .. 1_000_000 -> $n {
my $i = +$n.comb.sort.join;
++$cnt if Euler92($i) == 89;
}
 
say $cnt;
Output:
856929

All is not lost, however. Through the use of gradual typing, Perl 6 scales down as well as up, so this jit-friendly version is performant enough to brute force the larger calculation:

my @cache;
@cache[1] = 1;
@cache[89] = 89;
 
sub Euler92(int $n) {
$n < 649 # 99,999,999 sums to 648, so no point remembering more
?? (@cache.AT-POS($n) //= ids($n))
!! ids($n)
}
 
sub ids(int $num --> int) {
my int $n = $num;
my int $ten = 10;
my int $sum = 0;
my int $t;
my int $c;
repeat until $n == 89 or $n == 1 {
$sum = 0;
repeat {
$t = $n div $ten;
$c = $n - $t * $ten;
$sum = $sum + $c * $c;
} while $n = $t;
$n = @cache.AT-POS($sum) // $sum;
}
$n;
}
 
my int $cnt = 0;
for 1 .. 100_000_000 -> int $n {
$cnt = $cnt + 1 if Euler92($n) == 89;
}
say $cnt;
Output:
85744333

This runs in under ten minutes. We can reduce this to 4 minutes by writing in the NQP (Not Quite Perl6) subset of the language:

my $cache := nqp::list_i();
nqp::bindpos_i($cache, 650, 0);
nqp::bindpos_i($cache, 1, 1);
nqp::bindpos_i($cache, 89, 89);
 
sub Euler92(int $n) {
$n < 650
?? nqp::bindpos_i($cache,$n,ids($n))
!! ids($n)
}
 
sub ids(int $num --> int) {
my int $n = $num;
my int $ten = 10;
my int $sum = 0;
my int $t;
my int $c;
repeat until $n == 89 or $n == 1 {
$sum = 0;
repeat {
$t = nqp::div_i($n, $ten);
$c = $n - $t * $ten;
$sum = $sum + $c * $c;
} while $n = $t;
$n = nqp::atpos_i($cache,$sum) || $sum;
}
$n;
}
 
my int $cnt = 0;
for 1 .. 100_000_000 -> int $n {
$cnt = $cnt + 1 if Euler92($n) == 89;
}
say $cnt;

Phix[edit]

Translation of: C
constant MAXINT = iff(machine_bits()=32?9007199254740992
 :9223372036854775807)
 
procedure main(integer limit)
sequence sums = repeat(0,limit*81+1)
sums[1] = 1
for n=1 to limit do
for i=n*81 to 1 by -1 do
for j=1 to 9 do
integer s = j*j
if s>i then exit end if
sums[i+1] += sums[i+1-s]
end for
end for
atom count89 = 0
for i=1 to n*81 do
integer r, digit, w = i
while w!=1 do
r = 0
while w!=0 do
digit = mod(w,10)
r += digit*digit
w = floor(w/10)
end while
if r=89 then
count89 += sums[i+1]
if count89>MAXINT then
printf(1,"counter overflow for 10^%d\n",n)
return
end if
exit
end if
w = r
end while
end for
printf(1,"There are %d numbers from 1 to 10^%d ending with 89\n",{count89,n})
end for
end procedure
 
atom t0 = time()
main(20)
?time()-t0
Output:

on 32 bit:

There are 7 numbers from 1 to 10^1 ending with 89
There are 80 numbers from 1 to 10^2 ending with 89
There are 857 numbers from 1 to 10^3 ending with 89
There are 8558 numbers from 1 to 10^4 ending with 89
There are 85623 numbers from 1 to 10^5 ending with 89
There are 856929 numbers from 1 to 10^6 ending with 89
There are 8581146 numbers from 1 to 10^7 ending with 89
There are 85744333 numbers from 1 to 10^8 ending with 89
There are 854325192 numbers from 1 to 10^9 ending with 89
There are 8507390852 numbers from 1 to 10^10 ending with 89
There are 84908800643 numbers from 1 to 10^11 ending with 89
There are 850878696414 numbers from 1 to 10^12 ending with 89
There are 8556721999130 numbers from 1 to 10^13 ending with 89
There are 86229146720315 numbers from 1 to 10^14 ending with 89
There are 869339034137667 numbers from 1 to 10^15 ending with 89
There are 8754780882739336 numbers from 1 to 10^16 ending with 89
counter overflow for 10^17
0.031

same on 64-bit, but ending

There are 87975303595231975 numbers from 1 to 10^17 ending with 89
There are 881773944919974509 numbers from 1 to 10^18 ending with 89
There are 8816770037940618762 numbers from 1 to 10^19 ending with 89
counter overflow for 10^20
0.109

Combinatorics version[edit]

Following the steps outlined on the talk page.
I realised I needed to do this in two stages.
Phase 1. Make sure we can count.

function comb(sequence res, from, integer n, at=1, sequence chosen={})
if length(chosen)=n then
sequence digits = repeat(0,10)
for i=1 to length(chosen) do
digits[chosen[i]+1]+=1
end for
atom p = factorial(length(chosen))
for i=1 to 10 do
if digits[i] then
p /= factorial(digits[i])
end if
end for
res = sq_add(res,{p,1})
else
for i=at to length(from) do
res = comb(res,from,n,i,append(chosen,from[i]))
end for
end if
return res
end function
 
constant nums = {0,1,2,3,4,5,6,7,8,9}
for i=1 to 8 do
 ?comb({0,0},nums,i)
end for

Starting with the combinations method from http://rosettacode.org/wiki/Combinations_with_repetitions#Phix converted to a function, make sure we are covering all the numbers correctly by checking that we have indeed found power(10,n) of them, and show we are looking at significantly fewer combinations.

Output:
{10,10}
{100,55}
{1000,220}
{10000,715}
{100000,2002}
{1000000,5005}
{10000000,11440}
{100000000,24310}

Phase 2. Add in the rest of the logic, as suggested count 1's in preference to 89's and subtract from 10^n to get the answer.
[PS There is an eerie similarity between this and the 2nd C version, but I swear it is not a copy, and I noticed that later.]

sequence is1
 
function comb(atom res, sequence from, integer n, at=1, sequence chosen={})
if length(chosen)=n then
sequence digits = repeat(0,10)
atom sumsq = 0
for i=1 to length(chosen) do
integer ci = chosen[i]
sumsq += ci*ci
digits[ci+1]+=1
end for
if sumsq=0 or is1[sumsq] then
atom perms = factorial(length(chosen))
for i=1 to 10 do
if digits[i] then
perms /= factorial(digits[i])
end if
end for
res += perms
end if
else
for i=at to length(from) do
res = comb(res,from,n,i,append(chosen,from[i]))
end for
end if
return res
end function
 
procedure setis1(integer n)
is1 = repeat(0,n*81)
for i=1 to length(is1) do
integer r, digit, w = i
while 1 do
r = 0
while w!=0 do
digit = mod(w,10)
r += digit*digit
w = floor(w/10)
end while
if r=89 then exit end if
if r=1 then
is1[i] = 1
exit
end if
w = r
end while
end for
end procedure
 
constant nums = {0,1,2,3,4,5,6,7,8,9}
for i=1 to 16 do
atom t0 = time()
setis1(i)
printf(1,"There are %d numbers from 1 to 10^%d ending with 89 (%3.2fs)\n",{power(10,i)-comb(0,nums,i),i,time()-t0})
end for
Output:

Sadly, while still very much faster than brute force, several times slower than the translated from C version.

There are 7 numbers from 1 to 10^1 ending with 89 (0.00s)
There are 80 numbers from 1 to 10^2 ending with 89 (0.00s)
There are 857 numbers from 1 to 10^3 ending with 89 (0.00s)
There are 8558 numbers from 1 to 10^4 ending with 89 (0.00s)
There are 85623 numbers from 1 to 10^5 ending with 89 (0.02s)
There are 856929 numbers from 1 to 10^6 ending with 89 (0.00s)
There are 8581146 numbers from 1 to 10^7 ending with 89 (0.02s)
There are 85744333 numbers from 1 to 10^8 ending with 89 (0.02s)
There are 854325192 numbers from 1 to 10^9 ending with 89 (0.05s)
There are 8507390852 numbers from 1 to 10^10 ending with 89 (0.09s)
There are 84908800643 numbers from 1 to 10^11 ending with 89 (0.17s)
There are 850878696414 numbers from 1 to 10^12 ending with 89 (0.34s)
There are 8556721999130 numbers from 1 to 10^13 ending with 89 (0.58s)
There are 86229146720315 numbers from 1 to 10^14 ending with 89 (0.92s)
There are 869339034137667 numbers from 1 to 10^15 ending with 89 (1.66s)
There are 8754780882739337 numbers from 1 to 10^16 ending with 89 (2.75s)

PicoLisp[edit]

Brute force with caching

(de *Idx1or89 (89 . 89) ((1 . 1)))
 
(de 1or89 (N)
(let L (mapcar format (chop N))
(if (lup *Idx1or89 (setq N (sum * L L)))
(cdr @)
(prog1
(1or89 N)
(idx '*Idx1or89 (cons N @) T) ) ) ) )

Test:

(let Ones 0
(for I 100000000
(and (=1 (1or89 I)) (inc 'Ones)) )
(println (- 100000000 Ones)) )

Output:

85744333

PL/I[edit]

 
test: procedure options (main, reorder); /* 6 August 2015 */
 
declare (m, n) fixed decimal (10);
declare (i, j, p, s, tally initial (0) ) fixed binary (31);
declare d fixed binary (7);
declare (start_time, finish_time, elapsed_time) float (15);
 
start_time = secs();
 
do m = 1 to 1000000;
n = m;
do until ((n = 1) | (n = 89));
p = n; s = 0;
do while (p > 0);
d = mod(p, 10);
p = p/10;
s = s + d*d;
end;
n = s;
end;
if n = 89 then tally = tally + 1;
end;
 
finish_time = secs();
put skip edit (Tally, ' numbers iterated to 89') (f(10), A);
elapsed_time = finish_time - start_time;
put skip edit ('Elapsed time=', elapsed_time, ' secs') (A, F(10,3));
 
end test;
 

Output:

    856929 numbers iterated to 89
Elapsed time=    39.280 secs

PureBasic[edit]

Translation of: C
OpenConsole()
Procedure is89(x)
Repeat
s=0
While x : s+ x%10*x%10 : x/10 : Wend
If s=89 : ProcedureReturn 1 : EndIf
If s=1  : ProcedureReturn 0 : EndIf
x=s
ForEver
EndProcedure
 
Procedure main()
Dim sums(32*81+1) : sums(0)=1 : sums(1)=0
 
For n=1 To n+1
For i=n*81 To 1 Step -1
For j=1 To 9
s=j*j : If s>i : Break : EndIf
sums(i)+sums(i-s)
Next
Next
count89=0
For i=1 To n*81+1
If Not is89(i) : Continue : EndIf
If sums(i)>9223372036854775807-count89
PrintN("counter overflow for 10^"+Str(n))
ProcedureReturn 0
EndIf
count89+sums(i)
Next
PrintN("1->10^"+LSet(Str(n),2,Chr(32))+": "+Str(count89))
Next
EndProcedure
 
start=ElapsedMilliseconds()
main()
Print("elapsed milliseconds= "+Str(ElapsedMilliseconds()-start))
Input()
Output:
1->10^1 : 7
1->10^2 : 80
1->10^3 : 857
1->10^4 : 8558
1->10^5 : 85623
1->10^6 : 856929
1->10^7 : 8581146
1->10^8 : 85744333
1->10^9 : 854325192
1->10^10: 8507390852
1->10^11: 84908800643
1->10^12: 850878696414
1->10^13: 8556721999130
1->10^14: 86229146720315
1->10^15: 869339034137667
1->10^16: 8754780882739336
1->10^17: 87975303595231975
1->10^18: 881773944919974509
1->10^19: 8816770037940618762
counter overflow for 10^20
elapsed milliseconds= 9
Translation of: C++
OpenConsole()
Procedure sum_square_digits(n)
num=n : sum=0
While num>0
digit=num%10
num=(num-digit)/10
sum+ digit*digit
Wend
ProcedureReturn sum
EndProcedure
 
Procedure main()
i=0 : result=0 : count=0
For i=1 To 1e8
If Not i=1 Or Not i=89
result=sum_square_digits(i)
Else
result=i
EndIf
While Not result=1 And Not result=89
result=sum_square_digits(result)
Wend
If result=89 : count+1 : EndIf
Next
PrintN(Str(count))
EndProcedure
 
start=ElapsedMilliseconds()
main()
Print("elapsed milliseconds: "+Str(ElapsedMilliseconds()-start))
Input()
Output:
85744333
elapsed milliseconds: 65553

Python[edit]

Combinatorics[edit]

Translation of D[edit]

Translation of: D
from math import ceil, log10, factorial
 
def next_step(x):
result = 0
while x > 0:
result += (x % 10) ** 2
x /= 10
return result
 
def check(number):
candidate = 0
for n in number:
candidate = candidate * 10 + n
 
while candidate != 89 and candidate != 1:
candidate = next_step(candidate)
 
if candidate == 89:
digits_count = [0] * 10
for d in number:
digits_count[d] += 1
 
result = factorial(len(number))
for c in digits_count:
result /= factorial(c)
return result
 
return 0
 
def main():
limit = 100000000
cache_size = int(ceil(log10(limit)))
assert 10 ** cache_size == limit
 
number = [0] * cache_size
result = 0
i = cache_size - 1
 
while True:
if i == 0 and number[i] == 9:
break
if i == cache_size - 1 and number[i] < 9:
number[i] += 1
result += check(number)
elif number[i] == 9:
i -= 1
else:
number[i] += 1
for j in xrange(i + 1, cache_size):
number[j] = number[i]
i = cache_size - 1
result += check(number)
 
print result
 
main()
Output:
85744333

The run-time is less than half a second.

Translation of Ruby[edit]

Translation of: Ruby
 
from itertools import combinations_with_replacement
from array import array
from time import clock
D = 8
F = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000]
def b(n):
yield 1
for g in range(1,n+1):
gn = g
res = 0
while gn > 0:
gn,rem = divmod(gn,10)
res += rem**2
if res==89:
yield 0
else:
yield res
N = array('I',b(81*D))
for n in range(2,len(N)):
q = N[n]
while q>1:
q = N[q]
N[n] = q
 
es = clock()
z = 0
for n in combinations_with_replacement(range(10),D):
t = 0
for g in n:
t += g*g
if N[t] == 0:
continue
t = [0,0,0,0,0,0,0,0,0,0]
for g in n:
t[g] += 1
t1 = F[D]
for g in t:
t1 /= F[g]
z += t1
ee = clock() - es
print "\nD==" + str(D) + "\n " + str(z) + " numbers produce 1 and " + str(10**D-z) + " numbers produce 89"
print "Time ~= " + str(ee) + " secs"
 
Output:
D==8
 14255667 numbers produce 1 and 85744333 numbers produce 89
Time ~= 0.14 secs

D==11
15091199357 numbers produce 1 and 84908800643 numbers produce 89
Time ~= 1.12 secs

D==14
13770853279685 numbers produce 1 and 86229146720315 numbers produce 89
Time ~= 7.46 secs

D==17
12024696404768025 numbers produce 1 and 87975303595231975 numbers produce 89
Time ~= 34.16 secs

Python: Simple caching[edit]

>>> from functools import lru_cache
>>> @lru_cache(maxsize=1024)
def ids(n):
if n in {1, 89}: return n
else: return ids(sum(int(d) ** 2 for d in str(n)))
 
 
>>> ids(15)
89
>>> [ids(x) for x in range(1, 21)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1, 89]
>>> sum(ids(x) == 89 for x in range(1, 100000000))
85744333
>>>

This took a much longer time, in the order of hours.

Python: Enhanced caching[edit]

Notes that the order of digits in a number does not affect the final result so caches the digits of the number in sorted order for more hits.

>>> from functools import lru_cache
>>> @lru_cache(maxsize=1024)
def _ids(nt):
if nt in {('1',), ('8', '9')}: return nt
else: return _ids(tuple(sorted(str(sum(int(d) ** 2 for d in nt)))))
 
 
>>> def ids(n):
return int(''.join(_ids(tuple(sorted(str(n))))))
 
>>> ids(1), ids(15)
(1, 89)
>>> [ids(x) for x in range(1, 21)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1, 89]
>>> sum(ids(x) == 89 for x in range(1, 100000000))
85744333
>>> _ids.cache_info()
CacheInfo(hits=99991418, misses=5867462, maxsize=1024, currsize=1024)
>>>

This took tens of minutes to run.

Count digit sums[edit]

If we always count up to powers of 10, it's faster to just record how many different numbers have the same digit square sum. The check89() function is pretty simple-minded, because it doesn't need to be fancy here.

from __future__ import print_function
from itertools import count
 
def check89(n):
while True:
n, t = 0, n
while t: n, t = n + (t%10)**2, t//10
if n <= 1: return False
if n ==89: return True
 
a, sq, is89 = [1], [x**2 for x in range(1, 10)], [False]
for n in range(1, 500):
b, a = a, a + [0]*81
is89 += map(check89, range(len(b), len(a)))
 
for i,v in enumerate(b):
for s in sq: a[i + s] += v
 
x = sum(a[i] for i in range(len(a)) if is89[i])
print("10^%d" % n, x)

Racket[edit]

This contains two versions (in one go). The naive version which can (and should, probably) be used for investigating a single number. The second version can count the IDSes leading to 89 for powers of 10.

#lang racket
;; Tim-brown 2014-09-11
 
;; The basic definition.
;; It is possible to memoise this or use fixnum (native) arithmetic, but frankly iterating over a
;; hundred million, billion, trillion numbers will be slow. No matter how you do it.
(define (digit^2-sum n)
(let loop ((n n) (s 0))
(if (= 0 n) s (let-values ([(q r) (quotient/remainder n 10)]) (loop q (+ s (sqr r)))))))
 
(define (iterated-digit^2-sum n)
(match (digit^2-sum n) [0 0] [1 1] [89 89] [(app iterated-digit^2-sum rv) rv]))
 
;; Note that: ids(345) = ids(354) = ids(435) = ids(453) = ids(534) = ids(543) = 50 --> 89
;; One calculation does for 6 candidates.
;; The plan:
;; - get all the ordered combinations of digits including 0's which can be used both as digits and
;; "padding" digits in the most significant digits. (n.b. all-zeros is not in the range to be
;; tested and should be dropped)
;; - find the digit sets that have an IDS of 89
;; - find out how many combinations there are of these digits
 
;; output: a list of n-digits long lists containing all of the digit combinations.
;; a smart bunny would figure out the sums of the digits as they're generated but I'll plod
;; along step-by-step. a truly smart bunny would also count the combinations. that said, I
;; don't think I do much unnecessary computation here.
(define (all-digit-lists n-digits)
(define (inner remain acc least-digit)
(cond
[(zero? remain) (list (list))]
[(= least-digit 10) null]
[else
(for*/list
((ld+ (in-range least-digit 10))
(rgt (in-list (inner (sub1 remain) empty ld+))))
(append acc (cons ld+ rgt)))]))
(inner n-digits '() 0))
 
;; We calculate IDS differently since we're presented with a list of digits rather than a number
(define (digit-list-IDS c)
(define (digit-combo-IDS c)
(apply + (map sqr c)))
(iterated-digit^2-sum (digit-combo-IDS c)))
 
;; ! (factiorial) -- everyone's favourite combinatorial function! (that's just an exclamation mark)
;; there's one in (require math/number-theory) for any heavy lifting, but we're not or I could import
;; it from math/number-theory -- but this is about all I need. A lookup table is going to be faster
;; than a more general function.
(define (! n)
(case n [(0 1) 1] [(2) 2] [(3) 6] [(4) 24] [(5) 120] [(6) 720] [(7) 5040] [(8) 40320] [(9) 362880]
[else (* n (! (sub1 n)))] ; I expect this clause'll never be called
))
 
;; We need to count the permutations -- digits are in order so we can use the tail (cdr) function for
;; determining my various k's. See: https://en.wikipedia.org/wiki/Combination
(define (count-digit-list-permutations c #:length (l (length c)) #:length! (l! (! l)))
(let loop ((c c) (i 0) (prev -1 #;"never a digit") (p l!))
(match c
[(list) (/ p (! i))]
[(cons (== prev) d) (loop d (+ i 1) prev p)]
[(cons a d) (loop d 1 a (/ p (! i)))])))
 
;; Wrap it all up in a neat function
(define (count-89s-in-100... n)
(define n-digits (order-of-magnitude n))
(define combos (drop (all-digit-lists n-digits) 1)) ; don't want first one which is "all-zeros"
(for/sum ((c (in-list combos)) #:when (= 89 (digit-list-IDS c)))
(count-digit-list-permutations c #:length n-digits)))
 
(displayln "Testing permutations:")
(time (printf "1000000:\t~a~%" (count-89s-in-100... 1000000)))
(time (printf "100000000:\t~a~%" (count-89s-in-100... 100000000)))
(time (printf "1000000000:\t~a~%" (count-89s-in-100... 1000000000)))
(time (printf "1000000000000:\t~a~%" (count-89s-in-100... 1000000000000)))
(newline)
;; Do these last, since the 10^8 takes longer than my ADHD can cope with
(displayln "Testing one number at a time (somewhat slower):")
(time (printf "1000000:\t~a~%" (for/sum ((n (in-range 1 1000000))
#:when (= 89 (iterated-digit^2-sum n))) 1)))
(time (printf "100000000:\t~a~%" (for/sum ((n (in-range 1 100000000))
#:when (= 89 (iterated-digit^2-sum n))) 1)))
 
{module+ test
(require tests/eli-tester)
[test
(iterated-digit^2-sum 15) => 89
(iterated-digit^2-sum 7) => 1
(digit-combo-perms '()) => 1
(digit-combo-perms '(1 2 3)) => 6
(digit-combo-perms '(1 1 3)) => 3
(for/sum ((n (in-range 1 1000000)) #:when (= 89 (iterated-digit^2-sum n))) 1) => 856929
(all-digit-lists 1) => '((0) (1) (2) (3) (4) (5) (6) (7) (8) (9))
(length (all-digit-lists 2)) => 55
(length (all-digit-lists 3)) => 220
(count-89s-in-100... 1000000) => 856929]
}
Output:
Testing permutations:
1000000:	856929
cpu time: 8 real time: 8 gc time: 0
100000000:	85744333
cpu time: 44 real time: 43 gc time: 0
1000000000:	854325192
cpu time: 112 real time: 110 gc time: 20
1000000000000:	850878696414
cpu time: 1108 real time: 1110 gc time: 472

Testing one number at a time (somewhat slower):
1000000:	856929
cpu time: 1168 real time: 1171 gc time: 0
100000000:	85744333
cpu time: 130720 real time: 130951 gc time: 0

Ok, so maybe 131 seconds is not so flattering -- but I have not memoised or anything fancy like that, because even doing that isn't going to come anywhere near competing with 44ms.

REXX[edit]

{Both REXX versions don't depend on a specific end─number.}

with memoization[edit]

/*REXX program performs the squaring of iterated digits  (until the sum equals 1 or 89).*/
parse arg n . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n=10 * 1000000 /*Not specified? Then use the default.*/
!.=0; do m=1 for 9;  !.m=m**2; end /*m*/ /*build a short─cut for the squares. */
a.=. /*intermediate counts of some numbers. */
#.=0 /*count of 1 and 89 results so far.*/
do j=1 for n; x=j /* [↓] process the numbers in the range*/
do q=1 until s==89 | s==1; s=0 /*add sum of the squared decimal digits*/
do until x=='' /*process each of the dec. digits in X.*/
parse var x _ +1 x; s=s+!._ /*get a digit; sum the fast square, */
end /*until x== ... */ /* [↑] S≡is sum of the squared digits.*/
z.q=s /*assign sum to a temporary auxiliary. */
if a.s\==. then do; s=a.s; leave; end /*Found a previous sum? Then use that.*/
x=s /*substitute the sum for the "new" X. */
end /*until s== ... */ /* [↑] keep looping 'til S= 1 or 89.*/
 
do f=1 for q /* [↓] use the auxiliary array. */
_=z.f; a._=s /*assign auxiliaries for future look-up*/
end /*f*/
#.s=#.s+1 /*bump the counter for the 1's or 89's.*/
end /*j*/
 
do k=1 by 88 for 2; @=right('"'k'"', 5) /*display two results; define a literal*/
say 'count of' @ " chains for all natural numbers up to " n ' is:' #.k
end /*k*/ /*stick a fork in it, we're all done. */
output   when using the default input:


(ten million)

count of   "1"  chains for all natural numbers up to  10000000  is: 1418854
count of  "89"  chains for all natural numbers up to  10000000  is: 8581146

process in chunks[edit]

/*REXX program performs the squaring of iterated digits  (until the sum equals 1 or 89).*/
parse arg n . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n=10 * 1000000 /*Not specified? Then use the default.*/
!.=0; do m=1 for 9;  !.m=m**2; end /*m*/ /*build a short─cut for the squares. */
$.=.; $.0=0; $.00=0; $.000=0; $.0000=0; @.=. /*short-cuts for sub-group summations. */
#.=0 /*count of 1 and 89 results so far.*/
do j=1 for n; s=sumDs(j) /* [↓] process each number in a range.*/
#.s=#.s+1 /*bump the counter for 1's or 89's. */
end /*j*/
 
do k=1 by 88 for 2; @=right('"'k'"', 5) /*display two results; define a literal*/
say 'count of' @ " chains for all natural numbers up to " n ' is:' #.k
end /*k*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDs: parse arg z; chunk=3 /*obtain the number (for adding digits)*/
p=0 /*set partial sum of the decimal digits*/
do m=1 by chunk to length(z) /*process the number, in chunks of four*/
y=substr(z, m, chunk) /*extract a 4─byte chunk of the number.*/
if @.y==. then do; oy=y; a=0 /*Not done before? Then sum the number*/
do until y=='' /*process each of the dec. digits in Y.*/
parse var y _ +1 y; a=a+!._ /*obtain a decimal digit; add it to A.*/
end /*until y ···*/ /* [↑] A ≡ is the sum of squared digs*/
@.oy=a /*mark original Y as being summed. */
end
else [email protected].y /*use the pre─summed digits of Y. */
p=p+a /*add all the parts of number together.*/
end /*m*/
 
if $.p\==. then return $.p /*Computed before? Then use the value.*/
y=p /*use a new copy of P. */
do until s==1 | s==89; s=0 /*add the squared decimal digits of P.*/
do until y=='' /*process each decimal digits in X.*/
parse var y _ +1 y; s=s+!._ /*get a dec. digit; sum the fast square*/
end /*until y=='' ···*/ /* [↑] S ≡ is sum of the squared digs.*/
y=s /*substitute the sum for a "new" X. */
end /*until s==1 ···*/ /* [↑] keep looping 'til S=1 or 89.*/
$.p=s /*use this for memoization for the sum.*/
return s
output   when using the input of:   100000000


(one hundred million)

count of   "1"  chains for all natural numbers up to  100000000  is  14255667
count of  "89"  chains for all natural numbers up to  100000000  is  85744333

Ring[edit]

 
nr = 1000
num = 0
for n = 1 to nr
sum = 0
for m = 1 to len(string(n))
sum += pow(number(substr(string(n),m,1)),2)
if sum = 89 num += 1 see "" + n + " " + sum + nl ok
next
next
see "Total under 1000 is : " + num + nl
 

Output:

58 89
85 89
229 89
267 89
276 89
292 89
348 89
384 89
438 89
483 89
508 89
580 89
581 89
582 89
583 89
584 89
585 89
586 89
587 89
588 89
589 89
627 89
672 89
726 89
762 89
805 89
834 89
843 89
850 89
851 89
852 89
853 89
854 89
855 89
856 89
857 89
858 89
859 89
922 89
Total under 1000 is : 41

Ruby[edit]

# Count how many number chains for Natural Numbers < 10**d end with a value of 1.
def iterated_square_digit(d)
f = Array.new(d+1){|n| (1..n).inject(1, :*)} #Some small factorials
g = -> (n) { res = 0
while n>0
n, mod = n.divmod(10)
res += mod**2
end
res==89 ? 0 : res
}
 
#An array: table[n]==0 means that n translates to 89 and 1 means that n translates to 1
table = Array.new(d*81+1){|n| n.zero? ? 1 : (i=g.call(n))==89 ? 0 : i}
table.collect!{|n| n = table[n] while n>1; n}
z = 0 #Running count of numbers translating to 1
[*0..9].repeated_combination(d) do |rc| #Iterate over unique digit combinations
next if table[rc.inject(0){|g,n| g+n*n}].zero? #Count only ones
nn = [0] * 10 #Determine how many numbers this digit combination corresponds to
rc.each{|n| nn[n] += 1}
z += nn.inject(f[d]){|gn,n| gn / f[n]} #Add to the count of numbers terminating in 1
end
puts "\nd=(#{d}) in the range 1 to #{10**d-1}",
"#{z} numbers produce 1 and #{10**d-1-z} numbers produce 89"
end
 
[8, 11, 14, 17].each do |d|
t0 = Time.now
iterated_square_digit(d)
puts " #{Time.now - t0} sec"
end
Output:
d=(8) in the range 1 to 99999999
14255667 numbers produce 1 and 85744332 numbers produce 89
  0.116007 sec

d=(11) in the range 1 to 99999999999
15091199357 numbers produce 1 and 84908800642 numbers produce 89
  0.921052 sec

d=(14) in the range 1 to 99999999999999
13770853279685 numbers produce 1 and 86229146720314 numbers produce 89
  5.503315 sec

d=(17) in the range 1 to 99999999999999999
12024696404768025 numbers produce 1 and 87975303595231974 numbers produce 89
  24.337392 sec


Rust[edit]

These are two naive solutions, one with lots of redundant calculations (memoizationless recursion) and one with a few precomputed values. All digit square sums are no greater than 648 for numbers < 100_000_000.

Both are slow algorithms, however, Rust is among faster languages, so this doesn't take minutes or hours.

Naive Recursion

fn digit_square_sum(mut num: usize) -> usize {
let mut sum = 0;
while num != 0 {
sum += (num % 10).pow(2);
num /= 10;
}
sum
}
 
fn last_in_chain(num: usize) -> usize {
match num {
1 | 89 => num,
_ => last_in_chain(digit_square_sum(num)),
}
}
 
fn main() {
let count = (1..100_000_000).filter(|&n| last_in_chain(n) == 89).count();
println!("{}", count);
}
Output:
85744333

Runtime: 6s on a 2500k @ 4Ghz

With precomputation

fn dig_sq_sum(mut num : usize ) -> usize {
let mut sum = 0;
while num != 0 {
sum += (num % 10).pow(2);
num /= 10;
}
sum
}
 
fn last_in_chain(num: usize) -> usize {
match num {
0 => 0,
1 | 89 => num,
_ => last_in_chain(dig_sq_sum(num)),
}
}
 
fn main() {
let prec: Vec<_> = (0..649).map(|n| last_in_chain(n)).collect();
let count = (1..100_000_000).filter(|&n| prec[dig_sq_sum(n)] == 89).count();
println!("{}", count);
}

Runtime: 1.7s on a 2500k @ 4Ghz

Output:
85744333

Tcl[edit]

All three versions below produce identical output (85744333), but the third is fastest and the first is the slowest, both by substantial margins.

Very Naïve Version[edit]

proc ids n {
while {$n != 1 && $n != 89} {
set n [tcl::mathop::+ {*}[lmap x [split $n ""] {expr {$x**2}}]]
}
return $n
}
for {set i 1} {$i <= 100000000} {incr i} {
incr count [expr {[ids $i] == 89}]
}
puts $count

Intelligent Version[edit]

Conversion back and forth between numbers and strings is slow. Using math operations directly is much faster (around 4 times in informal testing).

proc ids n {
while {$n != 1 && $n != 89} {
for {set m 0} {$n} {set n [expr {$n / 10}]} {
incr m [expr {($n%10)**2}]
}
set n $m
}
return $n
}
for {set i 1} {$i <= 100000000} {incr i} {
incr count [expr {[ids $i] == 89}]
}
puts $count

Substantially More Intelligent Version[edit]

Using the observation that the maximum value after 1 step is obtained for 999999999, which is . Thus, running one step of the reduction and then using a lookup table (which we can construct quickly at the start of the run, and which has excellent performance) is much faster overall, approximately 3–4 times than the second version above (and over 12 times faster than the first version).

Donald, you have 1 too many 9's the value after step 1 is 81*8 = 648. Not that that is the problem here, you can not afford to go around this loop 100 million times. Notice that IDS[21] == IDS[12], IDS[123] == IDS[132] == IDS[213} ... etc, etc. The Ruby version takes about a tenth of a second.--Nigel Galloway (talk) 12:47, 31 August 2014 (UTC)
# Basic implementation
proc ids n {
while {$n != 1 && $n != 89} {
for {set m 0} {$n} {set n [expr {$n / 10}]} {
incr m [expr {($n%10)**2}]
}
set n $m
}
return $n
}
 
# Build the optimised version
set body {
# Microoptimisation to avoid an unnecessary alloc in the loop
for {set m 0} {$n} {set n [expr {"$n[unset n]" / 10}]} {
incr m [expr {($n%10)**2}]
}
}
set map 0
for {set i 1} {$i <= 729} {incr i} {
lappend map [ids $i]
}
proc ids2 n [append body "return \[lindex [list $map] \$m\]"]
 
# Put this in a lambda context for a little extra speed.
apply {{} {
set count 0
for {set i 1} {$i <= 100000000} {incr i} {
incr count [expr {[ids2 $i] == 89}]
}
puts $count
}}

VBScript[edit]

 
start_time = Now
cnt = 0
For i = 1 To 100000000
n = i
sum = 0
Do Until n = 1 Or n = 89
For j = 1 To Len(n)
sum = sum + (CLng(Mid(n,j,1))^2)
Next
n = sum
sum = 0
Loop
If n = 89 Then
cnt = cnt + 1
End If
Next
end_time = Now
 
WScript.Echo "Elapse Time: " & DateDiff("s",start_time,end_time) &_
vbCrLf & "Count: " & cnt
 
Output:

Elapse time is in seconds. Friends don't let friends do this in VBScript. :-)

Elapse Time: 2559
Count: 85744333

zkl[edit]

Using brute force is a never ending process so need to be clever, which takes under a second.

Translation of: Python
Translation of: D
fcn check(number){  // a list of digits: 13 is L(0,0,0,0,0,0,1,3)
candidate:=number.reduce(fcn(sum,n){ sum*10 + n },0); // digits to int
 
while(candidate != 89 and candidate != 1) // repeatedly sum squares of digits
{ candidate = candidate.split().reduce(fcn(sum,c){ sum + c*c },0); }
 
if(candidate == 89){ // count permutations of these digits, they all sum to 89
digitsCount:=List(0,0,0,0,0,0,0,0,0,0);
foreach d in (number){ digitsCount[d] += 1; }
return(digitsCount.reduce(fcn(r,c){ r/factorial(c) },cacheBang)); // cacheBang==number.len()!
}
0 // this number doesn't sum to 89 (ie sums to 1)
}
fcn factorial(n) { (1).reduce(n,fcn(N,n){ N*n },1) }
 
limit:=0d100_000_000; cacheSize:=limit.toFloat().log10().ceil().toInt();
number:=(0).pump(cacheSize,List().write,0); // list of zeros
result:=0; i:=cacheSize - 1;
var cacheBang=factorial(cacheSize); //== number.len()!
 
while(True){ // create numbers s.t. no set of digits is repeated
if(i == 0 and number[i] == 9) break;
if(i == cacheSize - 1 and number[i] < 9){ number[i] += 1; result += check(number); }
else if(number[i] == 9) i -= 1;
else{
number[i] += 1;
foreach j in ([i + 1 .. cacheSize - 1]){ number[j] = number[i]; }
i = cacheSize - 1;
result += check(number);
}
}
println(result);
Output:
85744333

ZX Spectrum Basic[edit]

Translation of: BBC_BASIC

Very, very slow. Use a ZX Spectrum emulator and run with maximum speed option enabled.

10 LET n=0
20 FOR i=1 TO 1000
30 LET j=i
40 LET k=0
50 LET k=INT (k+FN m(j,10)^2)
60 LET j=INT (j/10)
70 IF j<>0 THEN GO TO 50
80 LET j=k
90 IF j=89 OR j=1 THEN GO TO 100
95 GO TO 40
100 IF j>1 THEN LET n=n+1
110 NEXT i
120 PRINT "Version 1: ";n
200 DEF FN m(a,b)=a-INT (a/b)*b: REM modulo
Output:
Version 1: 857