aboutsummaryrefslogtreecommitdiff
path: root/challenge-133/abigail/awk/ch-2.awk
blob: b9d4e413f7260dfe6a520e66ba70f565e1682538 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/awk

#
# See ../README.md
#

#
# Run as: awk -f ch-2.awk < input-file
#

function digit_sum (number, sum) {
    sum = 0
    while (number > 0) {
        sum   += number % 10
        number = int (number / 10) 
    }
    return sum
}


#
# Factorize a number, given a set of small primes. This will work
# for numbers up to, but not including, p^2, where p is the smallest
# prime not included in the set. For the given set, the smallest number
# which fails to factorize is 37^2 == 1369.
#
# We'll return a string containing all the factors.
#
function factorize (n, out, i, prime, c) {
    out = ""
    c   = 0

    for (i in small_primes) {
        prime = small_primes [i]
        while (n % prime == 0) {
            out = out prime
            n  /= prime
            c ++
        }
    }
    
    if (n > 1) {
        out = out n
        c ++
    }

    return (c ";" out)
}

BEGIN {
    split ("2 3 5 7 11 13 17 19 23 29 31", small_primes, " ")
}

BEGIN {
    try   = 1
    count = 0
    while (count < 10) {
        split (factorize(try), info, ";")
        if (info [1] > 1 && digit_sum(try) == digit_sum(info [2])) {
            print try
            count ++
        }
        try ++
    }
}