How to resolve the algorithm Kaprekar numbers step by step in the AWK programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Kaprekar numbers step by step in the AWK programming language

Table of Contents

Problem Statement

A positive integer is a Kaprekar number if: Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive.

10000 (1002) splitting from left to right:

Generate and show all Kaprekar numbers less than 10,000.

Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.

The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too.

For this purpose, do the following:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Kaprekar numbers step by step in the AWK programming language

Source code in the awk programming language

# syntax: GAWK -f KAPREKAR_NUMBERS.AWK
BEGIN {
    limit = 1000000
    printf("%d\n",1)
    n = 1
    for (i=2; i<limit; i++) {
      squared = sprintf("%.0f",i*i)
      for (j=1; j<=length(squared); j++) {
        L = substr(squared,1,j) + 0
        R = substr(squared,j+1) + 0
        if (R == 0) {
          continue
        }
        if (L + R == i) {
          n++
          if (i <= 10000) {
            printf("%d\n",i)
          }
          break
        }
      }
    }
    printf("%d Kaprekar numbers < %s\n",n,limit)
    exit(0)
}


  

You may also check:How to resolve the algorithm Loops/Downward for step by step in the NewLISP programming language
You may also check:How to resolve the algorithm Isqrt (integer square root) of X step by step in the Swift programming language
You may also check:How to resolve the algorithm Literals/Integer step by step in the MIPS Assembly programming language
You may also check:How to resolve the algorithm Combinations and permutations step by step in the Ruby programming language
You may also check:How to resolve the algorithm Sort using a custom comparator step by step in the Oforth programming language