Weird numbers: Difference between revisions

m
(Crystal code)
m (→‎{{header|Wren}}: Minor tidy)
(43 intermediate revisions by 23 users not shown)
Line 1:
{{task}}
In number theory, a [[wp:weird number|weird number]] is a natural number that is [[wp:abundant number|abundant]] but ''not'' [[wp:semiperfect number|semiperfect]] (and therefore not [[wp:perfect number|perfect]] either).
 
In other words, the sum of the [[wp:Divisor#Further_notions_and_facts|proper divisors]] of the number (divisors including 1 but not itself) of the number 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:
 
E.G.* '''12''' is ''not'' a weird number. It is abundant; the proper divisors '''1, 2, 3, 4 & 6''' sum to '''16''', but it is semiperfect,
** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),
'''6 + 4 + 2 == 12'''.
** but it ''is'' semiperfect, e.g.:     '''6 + 4 + 2 == 12'''.
 
* '''70''' ''is'' a weird number. It is abundant; the proper divisors '''1, 2, 5, 7, 10, 14 & 35''' sum to '''74''', but there is no subset
of** It is abundant; its proper divisors that'''1, 2, 5, 7, 10, 14, 35''' sum to '''7074'''. (which ''is'' > 70),
** and there is no subset of proper divisors that sum to '''70'''.
 
 
Line 27 ⟶ 29:
<br>
 
=={{header|AppleScript11l}}==
{{trans|D}}
 
<syntaxhighlight lang="11l">F divisors(n)
V divs = [1]
[Int] divs2
V i = 2
L i * i <= n
I n % i == 0
V j = n I/ i
divs [+]= i
I i != j
divs2 [+]= j
i++
R divs2 [+] reversed(divs)
 
F abundant(n, divs)
R sum(divs) > n
 
F semiperfect(n, divs) -> Bool
I !divs.empty
V h = divs[0]
V t = divs[1..]
I n < h
R semiperfect(n, t)
E
R n == h | semiperfect(n - h, t) | semiperfect(n, t)
E
R 0B
 
F sieve(limit)
V w = [0B] * limit
L(i) (2 .< limit).step(2)
I w[i]
L.continue
V divs = divisors(i)
I !abundant(i, divs)
w[i] = 1B
E I semiperfect(i, divs)
L(j) (i .< limit).step(i)
w[j] = 1B
R w
 
V w = sieve(17'000)
V count = 0
print(‘The first 25 weird numbers:’)
L(n) (2..).step(2)
I !w[n]
print(n, end' ‘ ’)
count++
I count == 25
L.break</syntaxhighlight>
 
{{out}}
<pre>
The first 25 weird numbers:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310
</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Go}}
Translation of the untweaked Go version 1 sample. Avoids creating separate array slices in the semiperfect routine, to save memory for Algol 68G version 2.8.3.
<syntaxhighlight lang="algol68">BEGIN # find wierd numbers - abundant but not semiperfect numbers - translation of Go #
# returns the divisors of n in descending order #
PROC divisors = ( INT n )[]INT:
BEGIN
INT max divs = 2 * ENTIER sqrt( n );
[ 1 : max divs ]INT divs;
[ 1 : max divs ]INT divs2;
INT d pos := 0, d2 pos := 0;
divs[ d pos +:= 1 ] := 1;
FOR i FROM 2 WHILE i * i <= n DO
IF n MOD i = 0 THEN
INT j = n OVER i;
divs[ d pos +:= 1 ] := i;
IF i /= j THEN divs2[ d2 pos +:= 1 ] := j FI
FI
OD;
FOR i FROM d pos BY -1 WHILE i > 0 DO
divs2[ d2 pos +:= 1 ] := divs[ i ]
OD;
divs2[ 1 : d2 pos ]
END # divisors # ;
# returns TRUE if n with divisors divs, is abundant, FALSE otherwise #
PROC abundant = ( INT n, []INT divs )BOOL:
BEGIN
INT sum := 0;
FOR i FROM LWB divs TO UPB divs DO sum +:= divs[ i ] OD;
sum > n
END # abundant # ;
# returns TRUE if n with divisors divs, is semiperfect, FALSE otherwise #
PROC semiperfect = ( INT n, []INT divs, INT lb, ub )BOOL:
IF ub < lb
THEN FALSE
ELIF INT h = divs[ lb ];
n < h
THEN semiperfect( n, divs, lb + 1, ub )
ELIF n = h
THEN TRUE
ELIF semiperfect( n - h, divs, lb + 1, ub )
THEN TRUE
ELSE semiperfect( n, divs, lb + 1, ub )
FI # semiperfect # ;
# returns a sieve where FALSE = abundant and not semiperfect #
PROC sieve = ( INT limit )[]BOOL:
BEGIN # Only interested in even numbers >= 2 #
[ 1 : limit ]BOOL w; FOR i FROM 1 TO limit DO w[ i ] := FALSE OD;
FOR i FROM 2 BY 2 TO limit DO
IF NOT w[ i ] THEN
[]INT divs = divisors( i );
IF NOT abundant( i, divs ) THEN
w[ i ] := TRUE
ELIF semiperfect( i, divs, LWB divs, UPB divs ) THEN
FOR j FROM i BY i TO limit DO w[ j ] := TRUE OD
FI
FI
OD;
w
END # sieve # ;
BEGIN # task #
[]BOOL w = sieve( 17 000 );
INT count := 0;
INT max = 25;
print( ( "The first 25 weird numbers are:", newline ) );
FOR n FROM 2 BY 2 WHILE count < max DO
IF NOT w[ n ] THEN
print( ( whole( n, 0 ), " " ) );
count +:= 1
FI
OD;
print( ( newline ) )
END
END</syntaxhighlight>
{{out}}
<pre>
The first 25 weird numbers are:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310</pre>
 
=={{header|AppleScript}}==
===Functional===
Applescript is not the recommended apparatus for this kind of experiment.
 
(Though after about 6 seconds (on this system) it does yield the first 25, and intermediates can be logged in the Messages channel of macOS Script Editor).
 
<langsyntaxhighlight lang="applescript">on run
take(25, weirds())
-- Gets there, but takes about 6 seconds on this system,
Line 204 ⟶ 344:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>{70, 836, 4030, 5830, 7192, 7912, 9272, 10430, 10570, 10792, 10990, 11410, 11690, 12110, 12530, 12670, 13370, 13510, 13790, 13930, 14770, 15610, 15890, 16030, 16310}</pre>
----
 
===Idiomatic===
0.69 seconds:
 
<syntaxhighlight lang="applescript">-- Sum n's proper divisors.
on aliquotSum(n)
if (n < 2) then return 0
set sum to 1
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set sum to sum + limit
set limit to limit - 1
end if
repeat with i from 2 to limit
if (n mod i is 0) then set sum to sum + i + n div i
end repeat
return sum
end aliquotSum
 
-- Return n's proper divisors.
on properDivisors(n)
set output to {}
if (n > 1) then
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set end of output to limit
set limit to limit - 1
end if
repeat with i from limit to 2 by -1
if (n mod i is 0) then
set beginning of output to i
set end of output to n div i
end if
end repeat
set beginning of output to 1
end if
return output
end properDivisors
 
-- Does a subset of the given list of numbers add up to the target value?
on subsetOf:numberList sumsTo:target
script o
property lst : numberList
property someNegatives : false
on ssp(target, i)
repeat while (i > 1)
set n to item i of my lst
set i to i - 1
if ((n = target) or (((n < target) or (someNegatives)) and (ssp(target - n, i)))) then return true
end repeat
return (target = beginning of my lst)
end ssp
end script
-- The search can be more efficient if it's known the list contains no negatives.
repeat with n in o's lst
if (n < 0) then
set o's someNegatives to true
exit repeat
end if
end repeat
return o's ssp(target, count o's lst)
end subsetOf:sumsTo:
 
-- Is n a weird number?
on isWeird(n)
-- Yes if its aliquot sum's greater than it and no subset of its proper divisors adds up to it.
-- Using aliquotSum() to get the divisor sum and then calling properDivisors() too if a list's actually
-- needed is generally faster than calling properDivisors() in the first place and summing the result.
set sum to aliquotSum(n)
if (sum > n) then
set divisors to properDivisors(n)
-- Check that no subset sums to the smaller (usually the latter) of n and sum - n.
tell (sum - n) to if (it < n) then set n to it
return (not (my subsetOf:divisors sumsTo:n))
else
return false
end if
end isWeird
 
-- Task code:
on weirdNumbers(target)
script o
property weirds : {}
end script
set n to 2
set counter to 0
repeat until (counter = target)
if (isWeird(n)) then
set end of o's weirds to n
set counter to counter + 1
end if
set n to n + 1
end repeat
return o's weirds
end weirdNumbers
 
weirdNumbers(25)</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{70, 836, 4030, 5830, 7192, 7912, 9272, 10430, 10570, 10792, 10990, 11410, 11690, 12110, 12530, 12670, 13370, 13510, 13790, 13930, 14770, 15610, 15890, 16030, 16310}</syntaxhighlight>
 
=={{header|C}}==
{{trans|D}}
<langsyntaxhighlight lang="c">#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
Line 322 ⟶ 572:
free(w);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310</pre>
Line 328 ⟶ 578:
=={{header|C sharp|C#}}==
{{trans|D}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 407 ⟶ 657:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310</pre>
Line 413 ⟶ 663:
=={{header|C++}}==
{{trans|D}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <numeric>
Line 493 ⟶ 743:
std::cout << '\n';
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>The first 25 weird numbers:70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310</pre>
Line 499 ⟶ 749:
=={{header|Crystal}}==
{{trans|Go}}
<langsyntaxhighlight lang="ruby">def divisors(n : Int32) : Array(Int32)
divs = [1]
divs2 = [] of Int32
Line 508 ⟶ 758:
j = n // i
divs << i
divs2 << j if i != j
 
if i != j
divs2 << j
end
end
 
Line 593 ⟶ 840:
require "benchmark"
puts Benchmark.measure { main }
</syntaxhighlight>
</lang>
 
{{out}}
Line 604 ⟶ 851:
 
=={{header|D}}==
{{trans|Kotlin}} Adding efficient "cut" condition in semiperfect recursive algorithm
{{trans|Kotlin}}
<langsyntaxhighlight lang="d">import std.algorithm;
import std.array;
import std.stdio;
Line 630 ⟶ 877:
 
bool semiperfect(int n, int[] divs) {
if// This algorithm is O(2^N) for N == divs.length >when 0)number {is not semiperfect.
// Comparing with (divs.sum < n) instead (divs.length==0) removes unnecessary
// recursive binary tree branches.
auto s = divs.sum;
if(s == n)
return true;
else if ( s<n )
return false;
else {
auto h = divs[0];
auto t = divs[1..$];
Line 637 ⟶ 892:
} else {
return n == h
// Supossin h is part of the sum
|| semiperfect(n - h, t)
// Supossin h is not part of the sum
|| semiperfect(n, t);
}
} else {
return false;
}
}
 
Line 676 ⟶ 931:
}
writeln;
}</langsyntaxhighlight>
{{out}}
<pre>70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310</pre>
Line 682 ⟶ 937:
=={{header|F#|F sharp}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="fsharp">let divisors n = [1..n/2] |> List.filter (fun x->n % x = 0)
 
let abundant (n:int) divs = Seq.sum(divs) > n
Line 713 ⟶ 968:
i <- i + 1
 
0 // return an integer exit code</langsyntaxhighlight>
{{out}}
<pre>1 -> 70
Line 743 ⟶ 998:
=={{header|Factor}}==
The <code>has-sum?</code> word is a translation of the Haskell function.
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit io kernel lists lists.lazy
locals math math.primes.factors prettyprint sequences ;
IN: rosetta-code.weird-numbers
Line 769 ⟶ 1,024:
25 weirds ltake list>array . ;
 
MAIN: weird-numbers-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 801 ⟶ 1,056:
}
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
Function GetFactors(n As Long,r() As Long) As Long
Redim r(0)
r(0)=1
Dim As Long count,acc
For z As Long=2 To n\2
If n Mod z=0 Then
count+=1:redim preserve r(0 to count)
r(count)=z
acc+=z
End If
Next z
Return 1+acc
End Function
 
sub sumcombinations(arr() As Long,n As Long,r As Long,index As Long,_data() As Long,i As Long,Byref ans As Long,ref As Long)
Dim As Long acc
If index=r Then
For j As Long=0 To r-1
acc+=_data(j)
If acc=ref Then ans=1:Return
If acc>ref then return
Next j
Return
End If
If i>=n Or ans<>0 Then Return
_data(index) = arr(i)
sumcombinations(arr(),n,r,index + 1,_data(),i+1,ans,ref)
sumcombinations(arr(),n,r,index,_data(),i+1,ans,ref)
End sub
 
Function IsWeird(u() As Long,num As Long) As Long
Redim As Long d()
Dim As Long ans
For r As Long=2 To Ubound(u)
Redim d(r)
ans=0
sumcombinations(u(),Ubound(u)+1,r,0,d(),0,ans,num)
If ans =1 Then Return 0
Next r
Return 1
End Function
 
Redim As Long u()
Dim As Long SumFactors,number=2,count
Do
number+=2
SumFactors=GetFactors(number,u())
If SumFactors>number Then
If IsWeird(u(),number) Then Print number;" ";:count+=1
End If
Loop Until count=25
Print
Print "first 25 done"
Sleep
</syntaxhighlight>
{{out}}
<pre>
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310
first 25 done
</pre>
 
 
=={{header|Go}}==
Line 811 ⟶ 1,130:
 
When run on the same machine, the 'tweaked' version (linked to below), which was supplied by Enter your username, is almost 3 times faster than this.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 888 ⟶ 1,207:
}
fmt.Println()
}</langsyntaxhighlight>
 
{{out}}
Line 900 ⟶ 1,219:
=={{header|Haskell}}==
{{Trans|Python}}
<langsyntaxhighlight lang="haskell">weirds :: [Int]
weirds = filter abundantNotSemiperfect [1 ..]
 
Line 929 ⟶ 1,248:
main =
(putStrLn . unlines) $
zipWith (\i x -> show i ++ (" -> " ++ show x)) [1 ..] (take 25 weirds)</langsyntaxhighlight>
{{Out}}
<pre>1 -> 70
Line 959 ⟶ 1,278:
=={{header|J}}==
This algorithm uses a sieve to eliminate multiples of semiperfect numbers from future testing.
<syntaxhighlight lang="text">
factor=: [: }: [: , [: */&> [: { [: <@(^ i.@>:)/"1 [: |: __&q:
 
Line 1,001 ⟶ 1,320:
weird
)
</syntaxhighlight>
</lang>
<pre>
classify 20000 NB. the first 36 weird numbers
Line 1,008 ⟶ 1,327:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.List;
Line 1,082 ⟶ 1,401:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,116 ⟶ 1,435:
{{Trans|Python}}
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,230 ⟶ 1,549:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>1 -> 70
Line 1,257 ⟶ 1,576:
24 -> 16030
25 -> 16310</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Adapted from [[#Wren|Wren]]'''
 
For an explanation, see the [[#Go|Go]] entry.
 
The following also works with gojq, the Go implementation of jq, though much more slowly.
<syntaxhighlight lang=jq>
# unordered
def proper_divisors:
. as $n
| if $n > 1 then 1,
( range(2; 1 + (sqrt|floor)) as $i
| if ($n % $i) == 0 then $i,
(($n / $i) | if . == $i then empty else . end)
else empty
end)
else empty
end;
 
# Is n semiperfect given that divs are the proper divisors
def semiperfect(n; divs):
(divs|length) as $le
| if $le == 0 then false
else divs[0] as $h
| if n == $h then true
elif $le == 1 then false
else divs[1:] as $t
| if n < $h then semiperfect(n; $t)
else semiperfect(n-$h; $t) or semiperfect(n; $t)
end
end
end ;
 
def sieve(limit):
# 'false' denotes abundant and not semi-perfect.
# Only interested in even numbers >= 2
(reduce range(6; limit; 6) as $j ([]; .[$j] = true)) # eliminates multiples of 3
| reduce range(2; limit; 2) as $i (.;
if (.[$i]|not)
then [$i|proper_divisors] as $divs
| ($divs | add) as $sum
| if $sum <= $i
then .[$i] = true
elif (semiperfect($sum-$i; $divs))
then reduce range($i; limit; $i) as $j (.; .[$j] = true)
else .
end
else .
end) ;
 
# Print up to $max weird numbers based on the given sieve size, $limit.
def task($limit; $max):
sieve($limit) as $w
| def weirds:
range(2; $w|length; 2) | select($w[.]|not);
 
# collect into an array for ease of counting
[limit($max; weirds)]
| "The first \(length) weird numbers are:", . ;
 
# The parameters should be set on the command line:
task($sieve; $limit)
</syntaxhighlight>
'''Invocation:'''
 
jq -nrc --argjson sieve 16313 --argjson limit 25 -f weird.jq
{{output}}
<pre>
The first 25 weird numbers are:
[70,836,4030,5830,7192,7912,9272,10430,10570,10792,10990,11410,11690,12110,12530,12670,13370,13510,13790,13930,14770,15610,15890,16030,16310]
</pre>
 
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">using Primes
 
function nosuchsum(revsorted, num)
Line 1,303 ⟶ 1,696:
 
testweird(25)
</langsyntaxhighlight>{{out}}
<pre>
The first 25 weird numbers are:
Line 1,310 ⟶ 1,703:
 
=={{header|Kotlin}}==
{{trans|Go}}<langsyntaxhighlight lang="scala">// Version 1.3.21
 
fun divisors(n: Int): List<Int> {
Line 1,374 ⟶ 1,767:
}
println()
}</langsyntaxhighlight>
 
{{output}}
Line 1,381 ⟶ 1,774:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310
</pre>
 
=={{header|Lua}}==
{{trans|C#}}
<syntaxhighlight lang="lua">function make(n, d)
local a = {}
for i=1,n do
table.insert(a, d)
end
return a
end
 
function reverse(t)
local n = #t
local i = 1
while i < n do
t[i],t[n] = t[n],t[i]
i = i + 1
n = n - 1
end
end
 
function tail(list)
return { select(2, unpack(list)) }
end
 
function divisors(n)
local divs = {}
table.insert(divs, 1)
 
local divs2 = {}
 
local i = 2
while i * i <= n do
if n % i == 0 then
local j = n / i
table.insert(divs, i)
if i ~= j then
table.insert(divs2, j)
end
end
i = i + 1
end
 
reverse(divs)
for i,v in pairs(divs) do
table.insert(divs2, v)
end
return divs2
end
 
function abundant(n, divs)
local sum = 0
for i,v in pairs(divs) do
sum = sum + v
end
return sum > n
end
 
function semiPerfect(n, divs)
if #divs > 0 then
local h = divs[1]
local t = tail(divs)
if n < h then
return semiPerfect(n, t)
else
return n == h
or semiPerfect(n - h, t)
or semiPerfect(n, t)
end
else
return false
end
end
 
function sieve(limit)
-- false denotes abundant and not semi-perfect.
-- Only interested in even numbers >= 2
local w = make(limit, false)
local i = 2
while i < limit do
if not w[i] then
local divs = divisors(i)
if not abundant(i, divs) then
w[i] = true
elseif semiPerfect(i, divs) then
local j = i
while j < limit do
w[j] = true
j = j + i
end
end
end
i = i + 1
end
return w
end
 
function main()
local w = sieve(17000)
local count = 0
local max = 25
print("The first 25 weird numbers:")
local n = 2
while count < max do
if not w[n] then
io.write(n, ' ')
count = count + 1
end
n = n + 2
end
print()
end
 
main()</syntaxhighlight>
{{out}}
<pre>The first 25 weird numbers:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[WeirdNumberQ, HasSumQ]
HasSumQ[n_Integer, xs_List] := HasSumHelperQ[n, ReverseSort[xs]]
HasSumHelperQ[n_Integer, xs_List] := Module[{h, t},
If[Length[xs] > 0,
h = First[xs];
t = Drop[xs, 1];
If[n < h,
HasSumHelperQ[n, t]
,
n == h \[Or] HasSumHelperQ[n - h, t] \[Or] HasSumHelperQ[n, t]
]
,
False
]
]
WeirdNumberQ[n_Integer] := Module[{divs},
divs = Most[Divisors[n]];
If[Total[divs] > n,
! HasSumQ[n, divs]
,
False
]
]
r = {};
n = 0;
While[
Length[r] < 25,
If[WeirdNumberQ[++n], AppendTo[r, n]]
]
Print[r]</syntaxhighlight>
{{out}}
<pre>{70, 836, 4030, 5830, 7192, 7912, 9272, 10430, 10570, 10792, 10990, 11410, 11690, 12110, 12530, 12670, 13370, 13510, 13790, 13930, 14770, 15610, 15890, 16030, 16310}</pre>
 
=={{header|Nim}}==
{{trans|Go}}
<syntaxhighlight lang="nim">import algorithm, math, strutils
 
func divisors(n: int): seq[int] =
var smallDivs = @[1]
for i in 2..sqrt(n.toFloat).int:
if n mod i == 0:
let j = n div i
smallDivs.add i
if i != j: result.add j
result.add reversed(smallDivs)
 
func abundant(n: int; divs: seq[int]): bool {.inline.}=
sum(divs) > n
 
func semiperfect(n: int; divs: seq[int]): bool =
if divs.len > 0:
let h = divs[0]
let t = divs[1..^1]
result = if n < h: semiperfect(n, t)
else: n == h or semiperfect(n - h, t) or semiperfect(n, t)
 
func sieve(limit: int): seq[bool] =
# False denotes abundant and not semi-perfect.
# Only interested in even numbers >= 2.
result.setLen(limit)
for i in countup(2, limit - 1, 2):
if result[i]: continue
let divs = divisors(i)
if not abundant(i, divs):
result[i] = true
elif semiperfect(i, divs):
for j in countup(i, limit - 1, i):
result[j] = true
 
 
const Max = 25
let w = sieve(17_000)
var list: seq[int]
 
echo "The first 25 weird numbers are:"
var n = 2
while list.len != Max:
if not w[n]: list.add n
inc n, 2
echo list.join(" ")</syntaxhighlight>
 
{{out}}
<pre>The first 25 weird numbers are:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310</pre>
 
=={{header|Perl}}==
{{trans|Raku}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use strict;
use feature 'say';
 
Line 1,421 ⟶ 2,017:
}
 
say "The first 25 weird numbers:\n" . join ' ', @weird;</langsyntaxhighlight>
{{out}}
<pre>The first 25 weird numbers:
Line 1,429 ⟶ 2,025:
{{trans|Sidef}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use 5.010;
use strict;
use ntheory qw(vecsum divisors divisor_sum);
Line 1,462 ⟶ 2,058:
}
 
say "The first 25 weird numbers:\n@weird";</langsyntaxhighlight>
{{out}}
<pre>
Line 1,472 ⟶ 2,068:
{{trans|Go}}
Sufficiently fast that I un-optimised it a bit to make it easier to follow.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function abundant(integer n, sequence divs)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
return sum(divs) > n
<span style="color: #008080;">function</span> <span style="color: #000000;">abundant</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">divs</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">divs</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">></span> <span style="color: #000000;">n</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function semiperfect(integer n, sequence divs)
if length(divs)=0 then return false end if
<span style="color: #008080;">function</span> <span style="color: #000000;">semiperfect</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">divs</span><span style="color: #0000FF;">)</span>
integer h = divs[1]; divs = divs[2..$]
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">divs</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">false</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return n=h
<span style="color: #004080;">integer</span> <span style="color: #000000;">h</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">divs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">];</span> <span style="color: #000000;">divs</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">divs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
or (n>h and semiperfect(n-h, divs))
<span style="color: #008080;">return</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">h</span>
or semiperfect(n, divs)
<span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">h</span> <span style="color: #008080;">and</span> <span style="color: #000000;">semiperfect</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">h</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">divs</span><span style="color: #0000FF;">))</span>
end function
<span style="color: #008080;">or</span> <span style="color: #000000;">semiperfect</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">divs</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function sieve(integer limit)
-- true denotes abundant and not semi-perfect.
<span style="color: #008080;">function</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">)</span>
-- only interested in even numbers >= 2
<span style="color: #000080;font-style:italic;">-- true denotes abundant and not semi-perfect.
sequence wierd := repeat(true,limit)
-- only interested in even numbers &gt;= 2</span>
for j=6 to limit by 6 do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">wierd</span> <span style="color: #0000FF;">:=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">)</span>
-- eliminate multiples of 3
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">6</span> <span style="color: #008080;">to</span> <span style="color: #000000;">limit</span> <span style="color: #008080;">by</span> <span style="color: #000000;">6</span> <span style="color: #008080;">do</span>
wierd[j] = false
<span style="color: #000080;font-style:italic;">-- eliminate multiples of 3</span>
end for
<span style="color: #000000;">wierd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
for i=2 to limit by 2 do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if wierd[i] then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">limit</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
sequence divs := factors(i,-1)
<span style="color: #008080;">if</span> <span style="color: #000000;">wierd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
if not abundant(i,divs) then
<span style="color: #004080;">sequence</span> <span style="color: #000000;">divs</span> <span style="color: #0000FF;">:=</span> <span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
wierd[i] = false
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">abundant</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">divs</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
elsif semiperfect(i,divs) then
<span style="color: #000000;">wierd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
for j=i to limit by i do wierd[j] = false end for
<span style="color: #008080;">elsif</span> <span style="color: #000000;">semiperfect</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">divs</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end if
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">i</span> <span style="color: #008080;">to</span> <span style="color: #000000;">limit</span> <span style="color: #008080;">by</span> <span style="color: #000000;">i</span> <span style="color: #008080;">do</span> <span style="color: #000000;">wierd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return wierd
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">wierd</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
--constant MAX = 25, sieve_limit = 16313
constant MAX = 50, sieve_limit = 26533
<span style="color: #000080;font-style:italic;">--constant MAX = 25, sieve_limit = 16313 </span>
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">MAX</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">sieve_limit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">26533</span>
sequence wierd := sieve(sieve_limit), res = {}
for i=2 to sieve_limit by 2 do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">wierd</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sieve_limit</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
if wierd[i] then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">sieve_limit</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
res &= i
<span style="color: #008080;">if</span> <span style="color: #000000;">wierd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
if length(res)=MAX then exit end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span>
end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">MAX</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,"The first %d weird numbers are: %v\n",{MAX,res})</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"weird numbers"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">))})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
<pre style="font-size: 11px">
70 836 4030 5830 7192 ... 24710 25130 25690 26110 26530 (50 weird numbers)
The first 50 weird numbers are: {70,836,4030,5830,7192,7912,9272,10430,10570,10792,10990,11410,11690,12110,12530,12670,13370,13510,13790,13930,14770,15610,15890,16030,16310,
16730,16870,17272,17570,17990,18410,18830,18970,19390,19670,19810,20510,21490,21770,21910,22190,23170,23590,24290,24430,24710,25130,25690,26110,26530}
</pre>
 
Line 1,527 ⟶ 2,125:
The first 50 seem to take c. 300 ms
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Weird numbers'''
 
from itertools import chain, count, islice, repeat
Line 1,769 ⟶ 2,367:
# MAIN ----------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>First 50 weird numbers:
Line 1,785 ⟶ 2,383:
 
Approx computation time: 284 ms</pre>
 
=={{header|Quackery}}==
 
<code>properdivisors</code> is defined at [[Proper divisors#Quackery]].
 
<syntaxhighlight lang="quackery"> [ stack ] is target ( --> s )
[ stack ] is success ( --> s )
[ stack ] is makeable ( --> s )
 
[ bit makeable take
2dup & 0 !=
dip [ | makeable put ] ] is made ( n --> b )
 
[ ' [ 0 ] swap
dup target put
properdivisors
0 over witheach +
target share > not iff
[ target release
2drop false ] done
true success put
0 makeable put
witheach
[ over witheach
[ over dip
[ +
dup target share = iff
[ false success replace
drop conclude ] done
dup target share < iff
[ dup made not iff
join else drop ]
else drop ] ]
success share not if conclude
drop ]
drop
target release
makeable release
success take ] is weird ( n --> b )
 
[] 0
[ 1+
dup weird if
[ tuck join swap ]
over size 25 = until ]
drop
echo</syntaxhighlight>
 
{{out}}
 
<pre>[ 70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310 ]
</pre>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">#lang racket
 
(require math/number-theory)
 
(define (abundant? n proper-divisors)
(> (apply + proper-divisors) n))
 
(define (semi-perfect? n proper-divisors)
(let recur ((ds proper-divisors) (n n))
(or (zero? n)
(and (positive? n)
(pair? ds)
(or (recur (cdr ds) n)
(recur (cdr ds) (- n (car ds))))))))
 
(define (weird? n)
(let ((proper-divisors (drop-right (divisors n) 1))) ;; divisors includes n
(and (abundant? n proper-divisors) (not (semi-perfect? n proper-divisors)))))
 
(module+ main
(let recur ((i 0) (n 1) (acc null))
(cond [(= i 25) (reverse acc)]
[(weird? n) (recur (add1 i) (add1 n) (cons n acc))]
[else (recur i (add1 n) acc)])))
 
(module+ test
(require rackunit)
(check-true (weird? 70))
(check-false (weird? 12)))</syntaxhighlight>
 
{{out}}
 
<pre>'(70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310)</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub abundant (\x) {
my @l = x.is-prime ?? 1 !! flat
1, (2 .. x.sqrt.floor).map: -> \d {
Line 1,813 ⟶ 2,499:
}
 
put "The first 25 weird numbers:\n", @weird[^25];</langsyntaxhighlight>
{{out}}
<pre>The first 25 weird numbers:
Line 1,820 ⟶ 2,506:
=={{header|REXX}}==
===vanilla version===
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays N weird numbers in a vertical format (with index).*/
parse arg n cols . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 25 n= 25 /*Not specified? Then use the default.*/
#if cols=='' 0| cols=="," then cols= 10 /* " " " " " " /*the count of weird numbers (so far).*/
w= 10 do j=2 by 2 until #==n /*examinewidth of a number in any column. even integers 'til have 'nuff*/
if cols>0 then say ' index │'center(' weird numbers', 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
idx= 1; $= /*index for the output list; $: 1 line*/
weirds= 0 /*the count of weird numbers (so far).*/
do j=2 by 2 until weirds==n /*examine even integers 'til have 'nuff*/
if \weird(j) then iterate /*Not a weird number? Then skip it. */
#weirds= #weirds + 1 /*bump the count of weird numbers. */
sayc= rightcommas(th(#j), 30) ' weird number is:' right(commas(j), 9) /*displaymaybe weirdadd #commas to the number. */
$= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/
if weirds//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
 
exit /*stick a fork in it, we're all done. */
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
say
say 'Found ' commas(weirds) ' weird numbers'
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do ic=length(_)-3 to 1 by -3; _=insert(',', _, ic); end; return _
th: parse arg th;return th||word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4))
/*──────────────────────────────────────────────────────────────────────────────────────*/
DaS: procedure; parse arg x 1 z 1,b; a= 1 /*get X,Z,B (the 1st arg); init A list.*/
r= 0; q= 1 /* [↓] ══integer square root══ ___ */
do while q<=z; q=q*4; end /*R: an integer which will be √ X */
do while q>1; q=q%4; _= z-r-q; r= r%2; if _>=0 then do; z=_; r= r+q; end
end /*while q>1*/ /* [↑] compute the integer sqrt of X.*/
sig= a /*initialize the sigma so far. ___ */
Line 1,876 ⟶ 2,575:
end
end /*cp*/
end /*part*/; return 1 /*no sum equal to X, so X is weird.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the inputdefault ofinputs: &nbsp; &nbsp; <tt> 50 </tt>}}
<pre>
index 1st weird number is: 70 weird numbers
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
2nd weird number is: 836
1 70 836 3rd weird4,030 number is: 5,830 4 7,030192 7,912 9,272 10,430 10,570 10,792
11 10,990 11,410 11,690 12,110 4th weird number12,530 is: 12,670 13,370 13,510 13,790 513,830930
21 14,770 15,610 15,890 5th weird number is:16,030 716,192310
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────
6th weird number is: 7,912
 
7th weird number is: 9,272
Found 25 weird numbers
8th weird number is: 10,430
9th weird number is: 10,570
10th weird number is: 10,792
11th weird number is: 10,990
12th weird number is: 11,410
13th weird number is: 11,690
14th weird number is: 12,110
15th weird number is: 12,530
16th weird number is: 12,670
17th weird number is: 13,370
18th weird number is: 13,510
19th weird number is: 13,790
20th weird number is: 13,930
21st weird number is: 14,770
22nd weird number is: 15,610
23rd weird number is: 15,890
24th weird number is: 16,030
25th weird number is: 16,310
26th weird number is: 16,730
27th weird number is: 16,870
28th weird number is: 17,272
29th weird number is: 17,570
30th weird number is: 17,990
31st weird number is: 18,410
32nd weird number is: 18,830
33rd weird number is: 18,970
34th weird number is: 19,390
35th weird number is: 19,670
36th weird number is: 19,810
37th weird number is: 20,510
38th weird number is: 21,490
39th weird number is: 21,770
40th weird number is: 21,910
41st weird number is: 22,190
42nd weird number is: 23,170
43rd weird number is: 23,590
44th weird number is: 24,290
45th weird number is: 24,430
46th weird number is: 24,710
47th weird number is: 25,130
48th weird number is: 25,690
49th weird number is: 26,110
50th weird number is: 26,530
</pre>
 
Line 1,935 ⟶ 2,592:
<br>them by prime numbers <big> &ge; </big> '''sigma(primitive weird numbers)''' &nbsp; to find higher weird numbers.
 
This version is about &nbsp; '''2300%''' &nbsp; times faster than the 1<sup>st</sup> REXX version for larger amount of numbers.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays N weird numbers in a vertical format (with index).*/
parse arg n hPcols . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 25 400 /*Not specified? Then use the default.*/
if hPcols=='' | hPcols=="," then hPcols= 1000 10 /* " " " " " " */
w= 10 /*width of a number in any column. */
call genP /*generate primes just past Hp. */
if cols>0 then say ' index │'center(' weird numbers', 1 + cols*(w+1) )
#= 0; !.= 0 /*the count of weird numbers (so far).*/
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
do j=2 by 2 until #==n /*examine even integers 'til have 'nuff*/
weirds= 0; if \weird(j) then iterate !!.= 0 /*Notthe acount of weird numbers number? (so Then skip itfar). */
idx= 1; #= # + 1 $= /*bumpindex for the countoutput oflist; weird numbers.$: 1 line*/
say right( th(#), 30)do j=2 by 2 until weirds==n ' weird number is:' /*examine even integers 'til have right( commas(j), 9)'nuff*/
doif a=1\weird(j) forthen Np;iterate if @.a<=sigma+j then iterate; _= j /*Not @.a; weird number? Then !skip it._= 1*/
weirds= weirds + 1 /*bump the count of weird numbers. */
end /*a*/
do a=1 for # until _>hp; if @.a<sigma+j then iterate; _= j*@.a; !!._= 1
end /*j*/
exit end /*stick a fork in it, we're all done. */
c= commas(j) /*maybe add commas to the number. */
$= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/
if weirds//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
 
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
say
say 'Found ' commas(weirds) ' weird numbers'
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do ic=length(_)-3 to 1 by -3; _=insert(',', _, ic); end; return _
th: parse arg th;return th||word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4))
/*──────────────────────────────────────────────────────────────────────────────────────*/
DaS: procedure; parse arg x 1 z 1,b; a= 1 /*get X,Z,B (the 1st arg); init A list.*/
r= 0; q= 1 /* [↓] ══integer square root══ ___ */
do while q<=z; q=q*4; end /*R: an integer which will be √ X */
do while q>1; q=q%4; _= z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end
end /*while q>1*/ /* [↑] compute the integer sqrt of X.*/
sig = a /*initialize the sigma so far. ___ */
do j=2 to r - (r*r==x) /*divide by some integers up to √ X */
if x//j==0 then do; a=a j; b= x%j b /*if ÷, add both divisors to α & ß. */
sig= sig +j +x%j /*bump the sigma (the sum of divisorsPdivisors).*/
end
end /*j*/ /* [↑] % is the REXX integer division*/
Line 1,969 ⟶ 2,638:
return sig a b /*return the divisors (both lists). */
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: hp= 1000 * n @.1= 2; @.2= 3; nP= 2 /*get high PPrime limit; define assign some2 vars.low primes*/
@.1=2; @.2=3; @.3=5; @.4=7; do j=@.nP+25=11 by 2 until/*define @some low primes.nP>hp /*only find odd primes from here on. */
do k=2 while k*k<=j #=5; s.#= @.# **2 /*dividenumber byof someprimes knownso lowfar; odd primes prime². */
if j // @.k==0 then iterate j /*Is [↓] J generate divisiblemore by P?primes Then ¬ primehigh.*/
do j=@.#+2 by 2 for max(0, end /*k*/ hp%2-@.#%2-1) /*find [↓]odd primes afrom primehere (J) has been foundon. */
parse var j '' -1 nP= nP+1_; if @.nP_== j 5 then iterate /*bumpJ prime count;divisible assignby prime5? to (right @.dig)*/
end if j// 3==0 then iterate /*j" " " 3? */
if j// 7==0 then iterate /*" " " 7? */
return
/* [↑] the above five lines saves time*/
do k=5 while s.k<=j /* [↓] divide by the known odd primes.*/
if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; s.#= j*j /*bump # of Ps; assign next P; P²; P# */
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
weird: procedure expose !!. sigma; parse arg x . /*obtain a # to be tested for weirdness*/
if x<70 | x//3==0 then return 0 then return 0 /*test if X is too low or multiple of 3*/
if !!.x then return 1 /*Is this a prime*previous #? Found one*/
parse value DaS(x) with sigma divs /*obtain sigma and the proper divisors.*/
if sigma<=x then return 0 /*X isn't abundant (sigma too small).*/
Line 1,993 ⟶ 2,668:
if a.df==. then return 0 /*Any divisor is equal to DF? Not weird*/
c= 0; u= 2**# /*zero combo counter; calc. power of 2.*/
do p=1 for u-2; c= c + 1 /*convert P──►binary with leading zeros*/
yy.c= strip( x2b( d2x(p) ), 'L', 0) /*store this particular combination. */
end /*p*/
Line 2,007 ⟶ 2,682:
end /*cp*/
end /*part*/
return 1 /*no sum equal to X, so X is weird.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; iswhen identical tousing the 1<sup>st</sup>default REXX version.inputs:}} <br><br>
<pre>
index │ weird numbers
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
1 │ 70 836 4,030 5,830 7,192 7,912 9,272 10,430 10,570 10,792
11 │ 10,990 11,410 11,690 12,110 12,530 12,670 13,370 13,510 13,790 13,930
21 │ 14,770 15,610 15,890 16,030 16,310 16,730 16,870 17,272 17,570 17,990
31 │ 18,410 18,830 18,970 19,390 19,670 19,810 20,510 21,490 21,770 21,910
41 │ 22,190 23,170 23,590 24,290 24,430 24,710 25,130 25,690 26,110 26,530
51 │ 26,810 27,230 27,790 28,070 28,630 29,330 29,470 30,170 30,310 30,730
61 │ 31,010 31,430 31,990 32,270 32,410 32,690 33,530 34,090 34,370 34,930
71 │ 35,210 35,630 36,470 36,610 37,870 38,290 38,990 39,410 39,830 39,970
81 │ 40,390 41,090 41,510 41,930 42,070 42,490 42,910 43,190 43,330 44,170
91 │ 44,870 45,010 45,290 45,710 46,130 46,270 47,110 47,390 47,810 48,370
101 │ 49,070 49,630 50,330 50,890 51,310 51,730 52,010 52,570 52,990 53,270
111 │ 53,830 54,110 55,090 55,790 56,630 56,770 57,470 57,610 57,890 58,030
121 │ 58,730 59,710 59,990 60,130 60,410 61,390 61,670 61,810 62,090 63,490
131 │ 63,770 64,330 65,030 65,590 65,870 66,290 66,710 67,690 67,970 68,390
141 │ 68,810 69,370 69,790 70,630 70,910 71,330 71,470 72,170 72,310 72,730
151 │ 73,430 73,570 74,270 74,410 74,830 76,090 76,370 76,510 76,790 77,210
161 │ 77,630 78,190 78,610 79,030 80,570 80,710 81,410 81,970 82,670 83,090
171 │ 83,510 84,070 84,910 85,190 85,610 86,030 86,170 86,590 87,430 88,130
181 │ 89,390 89,530 89,810 90,230 90,370 90,790 91,070 91,210 91,490 92,330
191 │ 92,470 92,890 95,270 95,690 96,110 96,670 97,930 98,630 99,610 99,890
201 │ 100,030 100,310 100,730 101,290 101,570 101,710 102,130 102,970 103,670 103,810
211 │ 104,090 104,230 104,510 104,930 105,770 106,610 107,170 108,010 108,430 108,710
221 │ 109,130 109,690 109,970 110,530 110,810 111,790 112,070 112,490 112,630 112,910
231 │ 113,330 113,470 113,890 114,590 115,990 116,410 116,690 116,830 118,510 118,790
241 │ 118,930 119,630 120,470 120,610 121,310 121,870 122,290 122,710 123,130 124,390
251 │ 124,810 125,090 125,230 126,070 126,770 127,610 128,170 129,290 130,270 130,690
261 │ 130,970 131,110 131,390 131,530 132,230 133,070 133,490 133,910 135,170 135,310
271 │ 136,430 136,570 138,110 138,530 139,090 139,510 139,790 139,930 140,210 140,770
281 │ 141,190 141,890 142,030 142,730 143,710 144,410 144,830 145,670 145,810 146,090
291 │ 146,230 146,930 147,770 147,910 149,030 149,170 149,590 149,870 150,010 150,710
301 │ 151,270 152,530 154,210 154,490 154,910 155,470 156,590 156,730 157,010 157,570
311 │ 158,690 158,830 159,110 159,670 160,090 160,510 160,790 161,630 161,770 163,310
321 │ 163,730 163,870 164,290 164,570 164,990 165,970 166,390 166,670 166,810 167,230
331 │ 167,510 167,930 168,770 169,190 169,610 170,590 170,870 171,290 172,130 172,690
341 │ 173,110 173,390 175,210 176,470 177,170 177,730 178,010 178,430 178,570 178,990
351 │ 180,530 181,370 181,510 182,630 183,190 183,470 184,310 185,290 185,990 186,130
361 │ 186,410 186,970 187,390 187,810 188,090 188,230 188,510 188,930 189,490 189,770
371 │ 189,910 190,330 191,030 191,170 191,870 192,430 192,710 193,690 194,390 195,230
381 │ 195,370 195,790 196,070 196,210 197,330 198,310 198,590 199,010 199,570 199,990
391 │ 200,270 201,530 202,090 202,790 203,210 203,630 204,190 204,890 205,730 206,710
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────
 
Found 400 weird numbers
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">def divisors(n)
divs = [1]
divs2 = []
 
i = 2
while i * i <= n
if n % i == 0 then
j = (n / i).to_i
divs.append(i)
if i != j then
divs2.append(j)
end
end
 
i = i + 1
end
 
divs2 += divs.reverse
return divs2
end
 
def abundant(n, divs)
return divs.sum > n
end
 
def semiperfect(n, divs)
if divs.length > 0 then
h = divs[0]
t = divs[1..-1]
if n < h then
return semiperfect(n, t)
else
return n == h || semiperfect(n - h, t) || semiperfect(n, t)
end
else
return false
end
end
 
def sieve(limit)
w = Array.new(limit, false)
i = 2
while i < limit
if not w[i] then
divs = divisors(i)
if not abundant(i, divs) then
w[i] = true
elsif semiperfect(i, divs) then
j = i
while j < limit
w[j] = true
j = j + i
end
end
end
i = i + 2
end
return w
end
 
def main
w = sieve(17000)
count = 0
max = 25
print "The first %d weird numbers:\n" % [max]
n = 2
while count < max
if not w[n] then
print n, " "
count = count + 1
end
n = n + 2
end
print "\n"
end
 
main()</syntaxhighlight>
{{out}}
<pre>The first 25 weird numbers:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang ="ruby">func is_pseudoperfect(n, d = n.divisors.slicefirst(0, -21), s = d.sum, m = d.end) {
 
return false if (m < 0)
Line 2,026 ⟶ 2,830:
 
func is_weird(n) {
(n.sigma > 2*n) &&  !is_pseudoperfect(n)
}
 
var w = (1..Inf -> lazy.grep(is_weird).first(25))
say "The first 25 weird numbers:\n#{w.join(' ')}"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,039 ⟶ 2,843:
=={{header|Visual Basic .NET}}==
Performance is now on par with the python version, (but not quite up the Go version's performance), I applied what I could after reading the comments made by '''Hout''' on the discussion page.<br/>This program is similar to the structure of the '''Go''' example. I found a couple of tweaks here and there to help with performance. For example, the divisors list is built on a single array instead of joining two, and it calculates the sum while creating the divisors list. The divisors list is headed by the difference between "n" and the sum of the divisors. The semiperfect() function checks for equality first (rather than chopping the head from the tail list first) to save a little more time. And of course, the parallel execution.<br/><br/>A new feature is that one can calculate weird numbers up to any reasonable number, just enter a command line parameter of more than zero. Another new feature is calculating weird numbers continuously until a key is pressed (like the spigot algorithm from the [[Pi]] task) - to do so, enter a command line parameter of less than 1.<br/>This has no sieve cache, as one must "know" beforehand what number to cache up to, (for best results). Since there is no cache (runs slower), I added the parallel execution to make it run faster.<br/>I haven't let it run long enough to see how high it can get before crashing, I suspect it should happen once the weird number being tested is around Int32.MaxValue (2,147,483,647). But long before that it will slow down quite a bit. It takes around 17 minutes to get to the 10,732nd weird number, which is the first over 7 million (7,000,210).
<langsyntaxhighlight lang="vbnet">Module Module1
 
Dim resu As New List(Of Integer)
Line 2,124 ⟶ 2,928:
End If
End Sub
End Module</langsyntaxhighlight>
{{out}}
Without any command line parameters:
Line 2,141 ⟶ 2,945:
<pre>6981310 6983108 6983270 6983690 6985090 6985510 6986630 6987190 6987610 6988030 6988310 6988730 6990130 6990970 6991390 6991468 6991670 6992930 6993070 6993490 6994610 6995030 6996484 6997270 6997970 6998110 6999230 6999370 7000210 7001330 7003010 7003172 7003430 7003990 7004830 7007210 7007630 7008890 7009030
Computation time was 17m 9.0062776s for the first 10742 weird numbers.</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn divisors(n int) []int {
mut divs := [1]
mut divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs << i
if i != j {
divs2 << j
}
}
}
for i := divs.len - 1; i >= 0; i-- {
divs2 << divs[i]
}
return divs2
}
fn abundant(n int, divs []int) bool {
mut sum := 0
for div in divs {
sum += div
}
return sum > n
}
fn semiperfect(n int, divs []int) bool {
le := divs.len
if le > 0 {
h := divs[0]
t := divs[1..]
if n < h {
return semiperfect(n, t)
} else {
return n == h || semiperfect(n-h, t) || semiperfect(n, t)
}
} else {
return false
}
}
fn sieve(limit int) []bool {
// false denotes abundant and not semi-perfect.
// Only interested in even numbers >= 2
mut w := []bool{len: limit}
for i := 2; i < limit; i += 2 {
if w[i] {
continue
}
divs := divisors(i)
if !abundant(i, divs) {
w[i] = true
} else if semiperfect(i, divs) {
for j := i; j < limit; j += i {
w[j] = true
}
}
}
return w
}
fn main() {
w := sieve(17000)
mut count := 0
max := 25
println("The first 25 weird numbers are:")
for n := 2; count < max; n += 2 {
if !w[n] {
print("$n ")
count++
}
}
println('')
}</syntaxhighlight>
 
{{out}}
<pre>
The first 25 weird numbers are:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-math}}
{{libheader|Wren-iterate}}
<syntaxhighlight lang="wren">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")</syntaxhighlight>
 
{{out}}
<pre>
The first 25 weird numbers are:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310
 
Took 144 milliseconds
</pre>
 
=={{header|XPL0}}==
{{trans|C}}
This runs on a Raspberry Pi. MAlloc in other versions of XPL0 work differently.
Takes about 1.3 seconds.
<syntaxhighlight lang "XPL0">def SizeOfInt = 4;
def \IntA\ Ptr, Size;
int Array(2);
 
func Divisors(N); \Returns a list of proper divisors for N
int N;
int Divs, Divs2, Out;
int I, J, C1, C2;
[C1:= 0; C2:= 0;
Divs:= MAlloc(N * SizeOfInt / 2);
Divs2:= MAlloc(N * SizeOfInt / 2);
Divs(C1):= 1; C1:= C1+1;
I:= 2;
while I*I <= N do
[if rem(N/I) = 0 then
[J:= N/I;
Divs(C1):= I; C1:= C1+1;
if I # J then
[Divs2(C2):= J; C2:= C2+1];
];
I:= I+1;
];
Out:= MAlloc((C1+C2) * SizeOfInt);
for I:= 0 to C2-1 do
Out(I):= Divs2(I);
for I:= 0 to C1-1 do
Out(C2+I):= Divs(C1-I-1);
Array(Ptr):= Out;
Array(Size):= C1 + C2;
Release(Divs);
Release(Divs2);
return Array;
];
 
func Abundant(N, Divs); \Returns 'true' if N is abundant
int N, Divs;
int Sum, I;
[Sum:= 0;
for I:= 0 to Divs(Size)-1 do
Sum:= Sum + Divs(Ptr,I);
return Sum > N;
];
 
func Semiperfect(N, Divs); \Returns 'true' if N is semiperfect
int N, Divs;
int H, T, TA(2);
[if Divs(Size) > 0 then
[H:= Divs(Ptr,0);
T:= Divs(Ptr)+SizeOfInt;
TA(Ptr):= T;
TA(Size):= Divs(Size)-1;
if N < H then
return Semiperfect(N, TA)
else return N = H or Semiperfect(N-H, TA) or Semiperfect(N, TA);
]
else return false;
];
 
func Sieve(Limit); \Return array of weird number indexes set 'false'
int Limit; \i.e. non-abundant and non-semiperfect
int W, Divs(2), I, J;
[W:= MAlloc(Limit * SizeOfInt);
for I:= 0 to Limit-1 do W(I):= 0; \for safety
I:= 2;
while I < Limit do
[if W(I) = 0 then
[Divs:= Divisors(I);
if not Abundant(I, Divs) then
W(I):= true
else if Semiperfect(I, Divs) then
[J:= I;
while J < Limit do
[W(J):= true;
J:= J+I;
];
];
];
I:= I+2;
];
Release(Divs(Ptr));
return W;
];
 
int W, Count, Max, N;
[W:= Sieve(17000);
Count:= 0;
Max:= 25;
Text(0, "The first 25 weird numbers:^m^j");
N:= 2;
while Count < Max do
[if not W(N) then
[IntOut(0, N); ChOut(0, ^ );
Count:= Count+1;
];
N:= N+2;
];
CrLf(0);
Release(W);
]</syntaxhighlight>
{{out}}
<pre>
The first 25 weird numbers:
70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310
</pre>
 
=={{header|zkl}}==
{{trans|Go}}
<langsyntaxhighlight lang="zkl">fcn properDivs(n){
if(n==1) return(T);
( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) )
Line 2,170 ⟶ 3,229:
}
w
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">w,count,max := sieve(17_000), 0, 25;
println("The first 25 weird numbers are:");
foreach n in ([2..* ,2]){
Line 2,177 ⟶ 3,236:
if(count>=max) break;
}
println();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits