Rebol3 Code Examplex


Abundant odd numbers

Find odd numbers whose proper divisors sum to more than the number itself.

Rebol [
    title: "Rosetta code: Abundant odd numbers"
    file:  %Abundant_odd_numbers.r3
    url:   https://rosettacode.org/wiki/Abundant_odd_numbers
    needs: 3.20.0 ;; because of the `prime?` native used
    ;@@ https://github.com/Oldes/Rebol3/discussions/140
]

sum-proper-divisors: function[
    "Compute the sum of proper divisors of n"
    n [number!]
][
    db: clear []  ;; List to store divisors
    ;; Iterate divisors up to sqrt(n)
    for div 1 to integer! square-root n 1 [
        if zero? n % div [     ;; If div divides n exactly
            append db div      ;; Add the divisor
            append db n / div  ;; Add the paired divisor
        ]
    ]
    ;; Sum unique divisors and exclude the number itself
    (sum unique db) - n
]

billion: 1'000'000'000         ;; One billion constant
n: ix: 1                       ;; Initialize current number and index

print "The first 25 abundant odd numbers:"

forever [
    n: n + 2                         ;; Move to the next odd number
    if prime? n [continue]           ;; Skip primes (never abundant)
    prop-div: sum-proper-divisors n  ;; Calculate proper divisor sum
    if prop-div <= n [continue]      ;; Not abundant if sum ≤ n

    ;; Handle reporting for milestones and early results
    case [
        ix <= 25 [
            print [pad n -5 ":" prop-div]  ;; List first 25 found
        ]
        ix = 1000 [
            print ["1000th abundant odd number:" n ":" prop-div]
            n: billion + 1                 ;; Skip ahead
        ]
        n > billion [
            print ["First abundant odd number > 1'000'000'000:" n ":" prop-div]
            break                          ;; Exit after this milestone
        ]
    ]
    ++ ix  ;; Increment index of abundant odd numbers found
]

Output:

The first 25 abundant odd numbers:
  945 : 975
 1575 : 1649
 2205 : 2241
 2835 : 2973
 3465 : 4023
 4095 : 4641
 4725 : 5195
 5355 : 5877
 5775 : 6129
 5985 : 6495
 6435 : 6669
 6615 : 7065
 6825 : 7063
 7245 : 7731
 7425 : 7455
 7875 : 8349
 8085 : 8331
 8415 : 8433
 8505 : 8967
 8925 : 8931
 9135 : 9585
 9555 : 9597
 9765 : 10203
10395 : 12645
11025 : 11946
1000th abundant odd number: 492975 : 519361
First abundant odd number > 1'000'000'000: 1000000575 : 1083561009