How to resolve the algorithm Iterated digits squaring step by step in the AWK programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Iterated digits squaring step by step in the AWK 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 AWK programming language

Source code in the awk programming language

# Usage: GAWK -f ITERATED_DIGITS_SQUARING.AWK
BEGIN {
    # Setup buffer for results up to 9*9*8
    for (i = 1; i <= 648; i++) {
        k = i
        do {
            k = squaredigitsum(k)
        } while ((k != 1) && (k != 89))
        if (k == 1) # This will give us 90 entries
            buffer[i] = ""
    }
    # Check sequence for every number
    pow10 = 1
    for (i = 1; i <= 100000000; i++) {
        count += (squaredigitsum(i) in buffer) ? 0 : 1
        if (i == pow10) {
            printf("1->10^%d: %d\n", length(i) - 1, count)
            pow10 *= 10
        }
    }
}
function squaredigitsum(n,    r) {
    while (n) {
        r += (n % 10) ^ 2
        n = int(n / 10)
    }
    return r
}


  

You may also check:How to resolve the algorithm Inheritance/Multiple step by step in the Ruby programming language
You may also check:How to resolve the algorithm Wieferich primes step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the dc programming language
You may also check:How to resolve the algorithm Gapful numbers step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Sierpinski carpet step by step in the MATLAB programming language