How to resolve the algorithm Iterated digits squaring step by step in the PureBasic programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Iterated digits squaring step by step in the PureBasic programming language
Table of Contents
Problem Statement
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: An example in Python:
Or, for much less credit - (showing that your algorithm and/or language is slow): This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Iterated digits squaring step by step in the PureBasic programming language
Source code in the purebasic programming language
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()
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()
You may also check:How to resolve the algorithm Composite numbers k with no single digit factors whose factors are all substrings of k step by step in the Delphi programming language
You may also check:How to resolve the algorithm String length step by step in the MAXScript programming language
You may also check:How to resolve the algorithm Atomic updates step by step in the Java programming language
You may also check:How to resolve the algorithm Command-line arguments step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Shoelace formula for polygonal area step by step in the Julia programming language