How to resolve the algorithm Weird numbers step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Weird numbers step by step in the Wren programming language

Table of Contents

Problem Statement

In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example:

Find and display, here on this page, the first 25 weird numbers.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Weird numbers step by step in the Wren programming language

Source code in the wren programming language

import "/math" for Int, Nums
import "/iterate" for Stepped

var semiperfect // recursive
semiperfect = Fn.new { |n, divs|
    var le = divs.count
    if (le == 0) return false
    var h = divs[0]
    if (n == h) return true
    if (le == 1) return false
    var t = divs[1..-1]
    if (n < h) return semiperfect.call(n, t)
    return semiperfect.call(n-h, t) || semiperfect.call(n, t)
}

var sieve = Fn.new { |limit|
    // 'false' denotes abundant and not semi-perfect.
    // Only interested in even numbers >= 2
    var w = List.filled(limit, false)
    for (j in Stepped.new(6...limit, 6)) w[j] = true // eliminate multiples of 3
    for (i in Stepped.new(2...limit, 2)) {
        if (!w[i]) {
            var divs = Int.properDivisors(i)
            var sum = Nums.sum(divs)
            if (sum <= i) {
                w[i] = true
            } else if (semiperfect.call(sum-i, divs)) {
                for (j in Stepped.new(i...limit, i)) w[j] = true
            }
        }
    }
    return w
}

var start = System.clock
var limit = 16313
var w = sieve.call(limit)
var count = 0
var max = 25
System.print("The first 25 weird numbers are:")
var n = 2
while (count < max) {
    if (!w[n]) {
        System.write("%(n) ")
        count = count + 1
    }
    n = n + 2
}
System.print()
System.print("\nTook %(((System.clock-start)*1000).round) milliseconds")

  

You may also check:How to resolve the algorithm Draw a clock step by step in the Wren programming language
You may also check:How to resolve the algorithm Integer comparison step by step in the Forth programming language
You may also check:How to resolve the algorithm Exponentiation operator step by step in the VBA programming language
You may also check:How to resolve the algorithm Gauss-Jordan matrix inversion step by step in the Java programming language
You may also check:How to resolve the algorithm MD5 step by step in the PHP programming language