How to resolve the algorithm Arithmetic numbers step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Arithmetic numbers step by step in the Wren programming language
Table of Contents
Problem Statement
A positive integer n is an arithmetic number if the average of its positive divisors is also an integer. Clearly all odd primes p must be arithmetic numbers because their only divisors are 1 and p whose sum is even and hence their average must be an integer. However, the prime number 2 is not an arithmetic number because the average of its divisors is 1.5. 30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. Calculate and show here:
- The first 100 arithmetic numbers.
- The xth arithmetic number where x = 1,000 and x = 10,000.
- How many of the first x arithmetic numbers are composite. Note that, technically, the arithmetic number 1 is neither prime nor composite. Carry out the same exercise in 2. and 3. above for x = 100,000 and x = 1,000,000.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Arithmetic numbers step by step in the Wren programming language
Source code in the wren programming language
import "./math" for Int, Nums
import "./fmt" for Fmt
import "./sort" for Find
var arithmetic = [1]
var primes = []
var limit = 1e6
var n = 3
while (arithmetic.count < limit) {
var divs = Int.divisors(n)
if (divs.count == 2) {
primes.add(n)
arithmetic.add(n)
} else {
var mean = Nums.mean(divs)
if (mean.isInteger) arithmetic.add(n)
}
n = n + 1
}
System.print("The first 100 arithmetic numbers are:")
Fmt.tprint("$3d", arithmetic[0..99], 10)
for (x in [1e3, 1e4, 1e5, 1e6]) {
var last = arithmetic[x-1]
Fmt.print("\nThe $,dth arithmetic number is: $,d", x, last)
var pcount = Find.nearest(primes, last) + 1
if (!Int.isPrime(last)) pcount = pcount - 1
var comp = x - pcount - 1 // 1 is not composite
Fmt.print("The count of such numbers <= $,d which are composite is $,d.", last, comp)
}
You may also check:How to resolve the algorithm McNuggets problem step by step in the Ruby programming language
You may also check:How to resolve the algorithm Parsing/RPN to infix conversion step by step in the Nim programming language
You may also check:How to resolve the algorithm Apply a callback to an array step by step in the Elena programming language
You may also check:How to resolve the algorithm Detect division by zero step by step in the Batch File programming language
You may also check:How to resolve the algorithm Xiaolin Wu's line algorithm step by step in the Python programming language