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

Published on 12 May 2024 09:40 PM

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

Table of Contents

Problem Statement

A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.

Traditionally the single digit numbers 0 through 9 are included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, 1001 -> 1 + 001 (prime), 10 + 01 (prime) 100 + 1 (prime). There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above 97393713331910, the largest one known.

Let's start with the solution:

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

Source code in the awk programming language

# syntax: GAWK -f MAGNANIMOUS_NUMBERS.AWK
# converted from C
BEGIN {
    magnanimous(1,45)
    magnanimous(241,250)
    magnanimous(391,400)
    exit(0)
}
function is_magnanimous(n,  p,q,r) {
    if (n < 10) { return(1) }
    for (p=10; ; p*=10) {
      q = int(n/p)
      r = n % p
      if (!is_prime(q+r)) { return(0) }
      if (q < 10) { break }
    }
    return(1)
}
function is_prime(n,  d) {
    d = 5
    if (n < 2) { return(0) }
    if (!(n % 2)) { return(n == 2) }
    if (!(n % 3)) { return(n == 3) }
    while (d*d <= n) {
      if (!(n % d)) { return(0) }
      d += 2
      if (!(n % d)) { return(0) }
      d += 4
    }
    return(1)
}
function magnanimous(start,stop,  count,i) {
    printf("%d-%d:",start,stop)
    for (i=0; count<stop; ++i) {
      if (is_magnanimous(i)) {
        if (++count >= start) {
          printf(" %d",i)
        }
      }
    }
    printf("\n")
}


  

You may also check:How to resolve the algorithm Sequence: smallest number greater than previous term with exactly n divisors step by step in the C programming language
You may also check:How to resolve the algorithm Operator precedence step by step in the Raku programming language
You may also check:How to resolve the algorithm Department numbers step by step in the Tiny BASIC programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the Nemerle programming language
You may also check:How to resolve the algorithm Evolutionary algorithm step by step in the M2000 Interpreter programming language