How to resolve the algorithm Weird numbers step by step in the Raku programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Weird numbers step by step in the Raku 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 Raku programming language
Source code in the raku programming language
sub abundant (\x) {
my @l = x.is-prime ?? 1 !! flat
1, (2 .. x.sqrt.floor).map: -> \d {
my \y = x div d;
next if y * d !== x;
d !== y ?? (d, y) !! d
};
(my $s = @l.sum) > x ?? ($s, |@l.sort(-*)) !! ();
}
my @weird = (2, 4, {|($_ + 4, $_ + 6)} ... *).map: -> $n {
my ($sum, @div) = $n.&abundant;
next unless $sum; # Weird number must be abundant, skip it if it isn't.
next if $sum / $n > 1.1; # There aren't any weird numbers with a sum:number ratio greater than 1.08 or so.
if $n >= 10430 and ($n %% 70) and ($n div 70).is-prime {
# It's weird. All numbers of the form 70 * (a prime 149 or larger) are weird
} else {
my $next;
my $l = @div.shift;
++$next and last if $_.sum == $n - $l for @div.combinations;
next if $next;
}
$n
}
put "The first 25 weird numbers:\n", @weird[^25];
You may also check:How to resolve the algorithm Sisyphus sequence step by step in the Raku programming language
You may also check:How to resolve the algorithm Matrix-exponentiation operator step by step in the Lua programming language
You may also check:How to resolve the algorithm Polynomial regression step by step in the HicEst programming language
You may also check:How to resolve the algorithm Catamorphism step by step in the Swift programming language
You may also check:How to resolve the algorithm Simulate input/Keyboard step by step in the Perl programming language