Proper divisors: Difference between revisions

Content added Content deleted
m (→‎{{header|langur}}: added langur revision no.)
m (syntax highlighting fixup automation)
Line 30: Line 30:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F proper_divs(n)
<syntaxhighlight lang="11l">F proper_divs(n)
R Array(Set((1 .. (n + 1) I/ 2).filter(x -> @n % x == 0 & @n != x)))
R Array(Set((1 .. (n + 1) I/ 2).filter(x -> @n % x == 0 & @n != x)))


Line 36: Line 36:


V (n, leng) = max(((1..20000).map(n -> (n, proper_divs(n).len))), key' pd -> pd[1])
V (n, leng) = max(((1..20000).map(n -> (n, proper_divs(n).len))), key' pd -> pd[1])
print(n‘ ’leng)</lang>
print(n‘ ’leng)</syntaxhighlight>


{{out}}
{{out}}
Line 47: Line 47:
{{trans|Rexx}}
{{trans|Rexx}}
This program uses two ASSIST macros (XDECO, XPRNT) to keep the code as short as possible.
This program uses two ASSIST macros (XDECO, XPRNT) to keep the code as short as possible.
<lang 360asm>* Proper divisors 14/06/2016
<syntaxhighlight lang="360asm">* Proper divisors 14/06/2016
PROPDIV CSECT
PROPDIV CSECT
USING PROPDIV,R13 base register
USING PROPDIV,R13 base register
Line 180: Line 180:
XDEC DS CL12
XDEC DS CL12
YREGS
YREGS
END PROPDIV</lang>
END PROPDIV</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 198: Line 198:
=={{header|Action!}}==
=={{header|Action!}}==
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
<lang Action!>BYTE FUNC GetDivisors(INT a INT ARRAY divisors)
<syntaxhighlight lang="action!">BYTE FUNC GetDivisors(INT a INT ARRAY divisors)
INT i,max
INT i,max
BYTE count
BYTE count
Line 256: Line 256:
OD
OD
PrintF("%I has %I proper divisors%E",ind,max)
PrintF("%I has %I proper divisors%E",ind,max)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Proper_divisors.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Proper_divisors.png Screenshot from Atari 8-bit computer]
Line 283: Line 283:
[[http://rosettacode.org/wiki/Amicable_pairs#Ada]], we define this routine as a function of a generic package:
[[http://rosettacode.org/wiki/Amicable_pairs#Ada]], we define this routine as a function of a generic package:


<lang Ada>generic
<syntaxhighlight lang="ada">generic
type Result_Type (<>) is limited private;
type Result_Type (<>) is limited private;
None: Result_Type;
None: Result_Type;
Line 301: Line 301:
else Process(N, First+1));
else Process(N, First+1));
end Generic_Divisors;</lang>
end Generic_Divisors;</syntaxhighlight>


Now we instantiate the ''generic package'' to solve the other two parts of the task. Observe that there are two different instantiations of the package: one to generate a list of proper divisors, another one to count the number of proper divisors without actually generating such a list:
Now we instantiate the ''generic package'' to solve the other two parts of the task. Observe that there are two different instantiations of the package: one to generate a list of proper divisors, another one to count the number of proper divisors without actually generating such a list:


<lang Ada>with Ada.Text_IO, Ada.Containers.Generic_Array_Sort, Generic_Divisors;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Containers.Generic_Array_Sort, Generic_Divisors;


procedure Proper_Divisors is
procedure Proper_Divisors is
Line 363: Line 363:
Natural'Image(Number_Count) & " proper divisors.");
Natural'Image(Number_Count) & " proper divisors.");
end;
end;
end Proper_Divisors; </lang>
end Proper_Divisors; </syntaxhighlight>


{{out}}
{{out}}
Line 382: Line 382:
===As required by the Task===
===As required by the Task===
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<lang algol68># MODE to hold an element of a list of proper divisors #
<syntaxhighlight lang="algol68"># MODE to hold an element of a list of proper divisors #
MODE DIVISORLIST = STRUCT( INT divisor, REF DIVISORLIST next );
MODE DIVISORLIST = STRUCT( INT divisor, REF DIVISORLIST next );


Line 473: Line 473:
, " divisors"
, " divisors"
, newline
, newline
) )</lang>
) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 492: Line 492:
Alternative version that uses a sieve-like approach for faster proper divisor counting.
Alternative version that uses a sieve-like approach for faster proper divisor counting.
<br><br>Note, in order to run this with Algol 68G under Windows (and possibly Linux) the heap size must be increased, see [[ALGOL_68_Genie#Using_a_Large_Heap]].
<br><br>Note, in order to run this with Algol 68G under Windows (and possibly Linux) the heap size must be increased, see [[ALGOL_68_Genie#Using_a_Large_Heap]].
<lang algol68>BEGIN # count proper divisors using a sieve-like approach #
<syntaxhighlight lang="algol68">BEGIN # count proper divisors using a sieve-like approach #
# find the first/only number in 1 : 20 000 and 1 : 64 000 000 with #
# find the first/only number in 1 : 20 000 and 1 : 64 000 000 with #
# the most divisors #
# the most divisors #
Line 529: Line 529:
max number := 64 000 000
max number := 64 000 000
OD
OD
END</lang>
END</syntaxhighlight>


{{out}}
{{out}}
Line 539: Line 539:
=={{header|ALGOL-M}}==
=={{header|ALGOL-M}}==
Algol-M's maximum allowed integer value of 16,383 prevented searching up to 20,000 for the number with the most divisors, so the code here searches only up to 10,000.
Algol-M's maximum allowed integer value of 16,383 prevented searching up to 20,000 for the number with the most divisors, so the code here searches only up to 10,000.
<lang algol>
<syntaxhighlight lang="algol">
BEGIN
BEGIN


Line 611: Line 611:


END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 633: Line 633:
===Functional===
===Functional===
{{Trans|JavaScript}}
{{Trans|JavaScript}}
<lang AppleScript>-- PROPER DIVISORS -----------------------------------------------------------
<syntaxhighlight lang="applescript">-- PROPER DIVISORS -----------------------------------------------------------


-- properDivisors :: Int -> [Int]
-- properDivisors :: Int -> [Int]
Line 762: Line 762:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{oneToTen:{{num:1, divisors:{1}}, {num:2, divisors:{1}}, {num:3, divisors:{1}},
<syntaxhighlight lang="applescript">{oneToTen:{{num:1, divisors:{1}}, {num:2, divisors:{1}}, {num:3, divisors:{1}},
{num:4, divisors:{1, 2}}, {num:5, divisors:{1}}, {num:6, divisors:{1, 2, 3}},
{num:4, divisors:{1, 2}}, {num:5, divisors:{1}}, {num:6, divisors:{1, 2, 3}},
{num:7, divisors:{1}}, {num:8, divisors:{1, 2, 4}}, {num:9, divisors:{1, 3}},
{num:7, divisors:{1}}, {num:8, divisors:{1, 2, 4}}, {num:9, divisors:{1, 3}},
{num:10, divisors:{1, 2, 5}}},
{num:10, divisors:{1, 2, 5}}},
mostDivisors:{num:18480, divisors:79}}</lang>
mostDivisors:{num:18480, divisors:79}}</syntaxhighlight>
----
----


===Idiomatic===
===Idiomatic===


<lang applescript>on properDivisors(n)
<syntaxhighlight lang="applescript">on properDivisors(n)
set output to {}
set output to {}
Line 819: Line 819:
set output to output as text
set output to output as text
set AppleScript's text item delimiters to astid
set AppleScript's text item delimiters to astid
return output</lang>
return output</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>"1's proper divisors: {}
<syntaxhighlight lang="applescript">"1's proper divisors: {}
2's proper divisors: {1}
2's proper divisors: {1}
3's proper divisors: {1}
3's proper divisors: {1}
Line 834: Line 834:


Largest number of proper divisors for any number from 1 to 20,000: 79
Largest number of proper divisors for any number from 1 to 20,000: 79
Numbers with this many: 15120, 18480"</lang>
Numbers with this many: 15120, 18480"</syntaxhighlight>


=={{header|Arc}}==
=={{header|Arc}}==
<syntaxhighlight lang="arc">
<lang Arc>


;; Given num, return num and the list of its divisors
;; Given num, return num and the list of its divisors
Line 884: Line 884:
(div-lists 20000)
(div-lists 20000)
;; This took about 10 minutes on my machine.
;; This took about 10 minutes on my machine.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<syntaxhighlight lang="arc">
<lang Arc>
(1 0)
(1 0)
(2 1)
(2 1)
Line 907: Line 907:
It is the number 18480.
It is the number 18480.
There are 2 numbers with this trait, and they are (18480 15120)
There are 2 numbers with this trait, and they are (18480 15120)
</syntaxhighlight>
</lang>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program proFactor.s */
/* program proFactor.s */
Line 1,080: Line 1,080:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 1,110: Line 1,110:


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>properDivisors: function [x] ->
<syntaxhighlight lang="rebol">properDivisors: function [x] ->
(factors x) -- x
(factors x) -- x


Line 1,127: Line 1,127:
]
]


print ["The number with the most proper divisors (" maxProperDivisors ") is" maxN]</lang>
print ["The number with the most proper divisors (" maxProperDivisors ") is" maxN]</syntaxhighlight>


{{out}}
{{out}}
Line 1,144: Line 1,144:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>proper_divisors(n) {
<syntaxhighlight lang="autohotkey">proper_divisors(n) {
Array := []
Array := []
if n = 1
if n = 1
Line 1,157: Line 1,157:
Array[i] := true
Array[i] := true
return Array
return Array
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>output := "Number`tDivisors`tCount`n"
Examples:<syntaxhighlight lang="autohotkey">output := "Number`tDivisors`tCount`n"
loop, 10
loop, 10
{
{
Line 1,175: Line 1,175:
output .= "`nNumber(s) in the range 1 to 20,000 with the most proper divisors:`n" numDiv.Pop() " with " maxDiv " divisors"
output .= "`nNumber(s) in the range 1 to 20,000 with the most proper divisors:`n" numDiv.Pop() " with " maxDiv " divisors"
MsgBox % output
MsgBox % output
return</lang>
return</syntaxhighlight>
{{out}}
{{out}}
<pre>Number Divisors Count
<pre>Number Divisors Count
Line 1,193: Line 1,193:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PROPER_DIVISORS.AWK
# syntax: GAWK -f PROPER_DIVISORS.AWK
BEGIN {
BEGIN {
Line 1,230: Line 1,230:
return
return
}
}
</syntaxhighlight>
</lang>
<p>output:</p>
<p>output:</p>
<pre>
<pre>
Line 1,252: Line 1,252:
{{works with|QBasic|1.1}}
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic>FUNCTION CountProperDivisors (number)
<syntaxhighlight lang="qbasic">FUNCTION CountProperDivisors (number)
IF number < 2 THEN CountProperDivisors = 0
IF number < 2 THEN CountProperDivisors = 0
count = 0
count = 0
Line 1,290: Line 1,290:
PRINT
PRINT
PRINT most; " has the most proper divisors, namely "; maxCount
PRINT most; " has the most proper divisors, namely "; maxCount
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,297: Line 1,297:


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang BASIC256>subroutine ListProperDivisors(limit)
<syntaxhighlight lang="basic256">subroutine ListProperDivisors(limit)
if limit < 1 then return
if limit < 1 then return
for i = 1 to limit
for i = 1 to limit
Line 1,338: Line 1,338:
print
print
print most; " has the most proper divisors, namely "; maxCount
print most; " has the most proper divisors, namely "; maxCount
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,345: Line 1,345:


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>FUNCTION CountProperDivisors (number)
<syntaxhighlight lang="qbasic">FUNCTION CountProperDivisors (number)
IF number < 2 THEN LET CountProperDivisors = 0
IF number < 2 THEN LET CountProperDivisors = 0
LET count = 0
LET count = 0
Line 1,382: Line 1,382:
PRINT
PRINT
PRINT most; "has the most proper divisors, namely"; maxCount
PRINT most; "has the most proper divisors, namely"; maxCount
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,389: Line 1,389:


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>sub ListProperDivisors(limit)
<syntaxhighlight lang="yabasic">sub ListProperDivisors(limit)
if limit < 1 then return : fi
if limit < 1 then return : fi
for i = 1 to limit
for i = 1 to limit
Line 1,429: Line 1,429:
print
print
print most, " has the most proper divisors, namely ", maxCount
print most, " has the most proper divisors, namely ", maxCount
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,437: Line 1,437:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang qbasic>
<syntaxhighlight lang="qbasic">
FUNCTION ProperDivisor(nr, show)
FUNCTION ProperDivisor(nr, show)


Line 1,468: Line 1,468:


PRINT "Most proper divisors for number in the range 1-20000: ", MagicNumber, " with ", MaxDivisors, " divisors."
PRINT "Most proper divisors for number in the range 1-20000: ", MagicNumber, " with ", MaxDivisors, " divisors."
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,487: Line 1,487:
===Brute Force===
===Brute Force===
C has tedious boilerplate related to allocating memory for dynamic arrays, so we just skip the problem of storing values altogether.
C has tedious boilerplate related to allocating memory for dynamic arrays, so we just skip the problem of storing values altogether.
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdbool.h>
Line 1,530: Line 1,530:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,547: Line 1,547:
===Number Theoretic===
===Number Theoretic===
There is no need to go through all the divisors if only the count is needed, this implementation refines the brute force approach by solving the second part of the task via a Number Theory formula. The running time is noticeably faster than the brute force method above. Output is same as the above.
There is no need to go through all the divisors if only the count is needed, this implementation refines the brute force approach by solving the second part of the task via a Number Theory formula. The running time is noticeably faster than the brute force method above. Output is same as the above.
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdbool.h>
Line 1,617: Line 1,617:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>namespace RosettaCode.ProperDivisors
<syntaxhighlight lang="csharp">namespace RosettaCode.ProperDivisors
{
{
using System;
using System;
Line 1,651: Line 1,651:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1: {}
<pre>1: {}
Line 1,666: Line 1,666:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <vector>
<syntaxhighlight lang="cpp">#include <vector>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <algorithm>
Line 1,704: Line 1,704:
return 0 ;
return 0 ;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,731: Line 1,731:


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {
function divisors(Integer int) =>
function divisors(Integer int) =>
Line 1,752: Line 1,752:
print("the number(s) with the most divisors between ``start`` and ``end`` is/are:
print("the number(s) with the most divisors between ``start`` and ``end`` is/are:
``mostDivisors?.item else "nothing"`` with ``mostDivisors?.key else "no"`` divisors");
``mostDivisors?.item else "nothing"`` with ``mostDivisors?.key else "no"`` divisors");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1 => []
<pre>1 => []
Line 1,768: Line 1,768:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(ns properdivisors
<syntaxhighlight lang="lisp">(ns properdivisors
(:gen-class))
(:gen-class))


Line 1,803: Line 1,803:
(println n " has " (count factors) " divisors"))
(println n " has " (count factors) " divisors"))


</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 1,823: Line 1,823:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Ideally, the smallest-divisor function would only try prime numbers instead of odd numbers.
Ideally, the smallest-divisor function would only try prime numbers instead of odd numbers.
<lang lisp>(defun proper-divisors-recursive (product &optional (results '(1)))
<syntaxhighlight lang="lisp">(defun proper-divisors-recursive (product &optional (results '(1)))
"(int,list)->list::Function to find all proper divisors of a +ve integer."
"(int,list)->list::Function to find all proper divisors of a +ve integer."
Line 1,858: Line 1,858:
(dotimes (i 10) (format t "~A:~A~%" (1+ i) (proper-divisors-recursive (1+ i))))
(dotimes (i 10) (format t "~A:~A~%" (1+ i) (proper-divisors-recursive (1+ i))))
(format t "Task 2:Count & list of numbers <=20,000 with the most Proper Divisors:~%~A~%"
(format t "Task 2:Count & list of numbers <=20,000 with the most Proper Divisors:~%~A~%"
(task #'proper-divisors-recursive)))</lang>
(task #'proper-divisors-recursive)))</syntaxhighlight>
{{out}}
{{out}}
<pre>CL-USER(10): (main)
<pre>CL-USER(10): (main)
Line 1,878: Line 1,878:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
{{Works with|Black Box Component Builder}}
{{Works with|Black Box Component Builder}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE RosettaProperDivisor;
MODULE RosettaProperDivisor;
IMPORT StdLog;
IMPORT StdLog;
Line 1,934: Line 1,934:


^Q RosettaProperDivisor.Do~
^Q RosettaProperDivisor.Do~
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,955: Line 1,955:
{{trans|Python}}
{{trans|Python}}
Currently the lambda of the filter allocates a closure on the GC-managed heap.
Currently the lambda of the filter allocates a closure on the GC-managed heap.
<lang d>void main() /*@safe*/ {
<syntaxhighlight lang="d">void main() /*@safe*/ {
import std.stdio, std.algorithm, std.range, std.typecons;
import std.stdio, std.algorithm, std.range, std.typecons;


Line 1,963: Line 1,963:
iota(1, 11).map!properDivs.writeln;
iota(1, 11).map!properDivs.writeln;
iota(1, 20_001).map!(n => tuple(properDivs(n).count, n)).reduce!max.writeln;
iota(1, 20_001).map!(n => tuple(properDivs(n).count, n)).reduce!max.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[[], [1], [1], [1, 2], [1], [1, 2, 3], [1], [1, 2, 4], [1, 3], [1, 2, 5]]
<pre>[[], [1], [1], [1, 2], [1], [1, 2, 3], [1], [1, 2, 4], [1, 3], [1, 2, 5]]
Line 1,971: Line 1,971:
=={{header|Delphi}}==
=={{header|Delphi}}==
{{trans|C#}}
{{trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program ProperDivisors;
program ProperDivisors;


Line 2,038: Line 2,038:
readln;
readln;
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,055: Line 2,055:


Version with TParallel.For
Version with TParallel.For
<syntaxhighlight lang="delphi">
<lang Delphi>
program ProperDivisors;
program ProperDivisors;


Line 2,123: Line 2,123:
readln;
readln;
end.
end.
</syntaxhighlight>
</lang>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
Line 2,129: Line 2,129:
{{trans|Swift}}
{{trans|Swift}}


<lang dyalect>func properDivs(n) {
<syntaxhighlight lang="dyalect">func properDivs(n) {
if n == 1 {
if n == 1 {
yield break
yield break
Line 2,153: Line 2,153:
}
}
print("\(num): \(max)")</lang>
print("\(num): \(max)")</syntaxhighlight>


{{out}}
{{out}}
Line 2,170: Line 2,170:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'list) ;; list-delete
(lib 'list) ;; list-delete


Line 2,214: Line 2,214:




</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang scheme>
<syntaxhighlight lang="scheme">
(for ((i (in-range 1 11))) (writeln i (divs i)))
(for ((i (in-range 1 11))) (writeln i (divs i)))
1 null
1 null
Line 2,237: Line 2,237:
(lib 'bigint)
(lib 'bigint)
(numdivs 95952222101012742144) → 666 ;; 🎩
(numdivs 95952222101012742144) → 666 ;; 🎩
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 2,293: Line 2,293:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,311: Line 2,311:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Proper do
<syntaxhighlight lang="elixir">defmodule Proper do
def divisors(1), do: []
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
Line 2,330: Line 2,330:
IO.puts "#{n}: #{inspect Proper.divisors(n)}"
IO.puts "#{n}: #{inspect Proper.divisors(n)}"
end)
end)
Proper.most_divisors(20000)</lang>
Proper.most_divisors(20000)</syntaxhighlight>


{{out}}
{{out}}
Line 2,349: Line 2,349:
=={{header|Erlang}}==
=={{header|Erlang}}==


<lang erlang>-module(properdivs).
<syntaxhighlight lang="erlang">-module(properdivs).
-export([divs/1,sumdivs/1,longest/1]).
-export([divs/1,sumdivs/1,longest/1]).


Line 2,375: Line 2,375:
longest(L,Acc,A,Acc+1);
longest(L,Acc,A,Acc+1);
true -> longest(L,Current,CurLeng,Acc+1)
true -> longest(L,Current,CurLeng,Acc+1)
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,396: Line 2,396:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
// the simple function with the answer
// the simple function with the answer
let propDivs n = [1..n/2] |> List.filter (fun x->n % x = 0)
let propDivs n = [1..n/2] |> List.filter (fun x->n % x = 0)
Line 2,416: Line 2,416:
|> Seq.fold (fun a b ->match a,b with | (_,c1,_),(_,c2,_) when c2 > c1 -> b | _-> a) (0,0,[])
|> Seq.fold (fun a b ->match a,b with | (_,c1,_),(_,c2,_) when c2 > c1 -> b | _-> a) (0,0,[])
|> fun (n,count,_) -> (n,count,[]) |> show
|> fun (n,count,_) -> (n,count,[]) |> show
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,434: Line 2,434:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: formatting io kernel math math.functions
<syntaxhighlight lang="factor">USING: formatting io kernel math math.functions
math.primes.factors math.ranges prettyprint sequences ;
math.primes.factors math.ranges prettyprint sequences ;


Line 2,443: Line 2,443:
10 [1,b] [ dup pprint bl divisors but-last . ] each
10 [1,b] [ dup pprint bl divisors but-last . ] each
20000 [1,b] [ #divisors ] supremum-by dup #divisors
20000 [1,b] [ #divisors ] supremum-by dup #divisors
"%d with %d divisors.\n" printf</lang>
"%d with %d divisors.\n" printf</syntaxhighlight>


{{out}}
{{out}}
Line 2,461: Line 2,461:


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>Func Divisors(n) =
<syntaxhighlight lang="fermat">Func Divisors(n) =
[d]:=[(1)]; {start divisor list with just 1, which is a divisor of everything}
[d]:=[(1)]; {start divisor list with just 1, which is a divisor of everything}
for i = 2 to n\2 do {loop through possible divisors of n}
for i = 2 to n\2 do {loop through possible divisors of n}
Line 2,484: Line 2,484:
od;
od;


!!('The number up to 20,000 with the most divisors was ',champ,' with ',record,' divisors.');</lang>
!!('The number up to 20,000 with the most divisors was ',champ,' with ',record,' divisors.');</syntaxhighlight>


{{out}}<pre>
{{out}}<pre>
Line 2,504: Line 2,504:
{{works with|gforth|0.7.3}}
{{works with|gforth|0.7.3}}


<lang forth>: .proper-divisors
<syntaxhighlight lang="forth">: .proper-divisors
dup 1 ?do
dup 1 ?do
dup i mod 0= if i . then
dup i mod 0= if i . then
Line 2,531: Line 2,531:
;
;


rosetta-proper-divisors</lang>
rosetta-proper-divisors</syntaxhighlight>


{{out}}
{{out}}
Line 2,551: Line 2,551:
=={{header|Fortran}}==
=={{header|Fortran}}==
Compiled using G95 compiler, run on x86 system under Puppy Linux
Compiled using G95 compiler, run on x86 system under Puppy Linux
<syntaxhighlight lang="fortran">
<lang Fortran>
function icntprop(num )
function icntprop(num )
Line 2,582: Line 2,582:
print *,maxj,' has max proper divisors: ',maxcnt
print *,maxj,' has max proper divisors: ',maxcnt
end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,620: Line 2,620:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
' FreeBASIC v1.05.0 win64
' FreeBASIC v1.05.0 win64


Line 2,668: Line 2,668:
Sleep
Sleep
End
End
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,689: Line 2,689:


=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
<lang pascal>
<syntaxhighlight lang="pascal">
Program ProperDivisors;
Program ProperDivisors;


Line 2,748: Line 2,748:
list.free;
list.free;
End.
End.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,767: Line 2,767:
Frink's built-in factorization routines efficiently find factors of arbitrary-sized integers.
Frink's built-in factorization routines efficiently find factors of arbitrary-sized integers.


<lang frink>
<syntaxhighlight lang="frink">
for n = 1 to 10
for n = 1 to 10
println["$n\t" + join[" ", properDivisors[n]]]
println["$n\t" + join[" ", properDivisors[n]]]
Line 2,784: Line 2,784:


properDivisors[n] := allFactors[n, true, false, true]
properDivisors[n] := allFactors[n, true, false, true]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,803: Line 2,803:
=={{header|GFA Basic}}==
=={{header|GFA Basic}}==


<lang>
<syntaxhighlight lang="text">
OPENW 1
OPENW 1
CLEARW 1
CLEARW 1
Line 2,879: Line 2,879:
RETURN count%-1
RETURN count%-1
ENDFUNC
ENDFUNC
</syntaxhighlight>
</lang>


Output is:
Output is:
Line 2,898: Line 2,898:
=={{header|Go}}==
=={{header|Go}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,959: Line 2,959:
fmt.Println(n)
fmt.Println(n)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,983: Line 2,983:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>import Data.Ord
<syntaxhighlight lang="haskell">import Data.Ord
import Data.List
import Data.List


Line 2,995: Line 2,995:
putStrLn "a number with the most divisors within 1 to 20000 (number, count):"
putStrLn "a number with the most divisors within 1 to 20000 (number, count):"
print $ maximumBy (comparing snd)
print $ maximumBy (comparing snd)
[(n, length $ divisors n) | n <- [1 .. 20000]]</lang>
[(n, length $ divisors n) | n <- [1 .. 20000]]</syntaxhighlight>
{{out}}
{{out}}
<pre>divisors of 1 to 10:
<pre>divisors of 1 to 10:
Line 3,013: Line 3,013:
For a little more efficiency, we can filter only up to the root – deriving the higher proper divisors from the lower ones, as quotients:
For a little more efficiency, we can filter only up to the root – deriving the higher proper divisors from the lower ones, as quotients:


<lang haskell>import Data.List (maximumBy)
<syntaxhighlight lang="haskell">import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.Ord (comparing)
import Data.Bool (bool)
import Data.Bool (bool)
Line 3,038: Line 3,038:
print $
print $
maximumBy (comparing snd) $
maximumBy (comparing snd) $
(,) <*> (length . properDivisors) <$> [1 .. 20000]</lang>
(,) <*> (length . properDivisors) <$> [1 .. 20000]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Proper divisors of 1 to 10:
<pre>Proper divisors of 1 to 10:
Line 3,059: Line 3,059:
and we can also define properDivisors in terms of primeFactors:
and we can also define properDivisors in terms of primeFactors:


<lang haskell>import Data.Numbers.Primes (primeFactors)
<syntaxhighlight lang="haskell">import Data.Numbers.Primes (primeFactors)
import Data.List (group, maximumBy, sort)
import Data.List (group, maximumBy, sort)
import Data.Ord (comparing)
import Data.Ord (comparing)
Line 3,091: Line 3,091:
w = maximum (length . xShow <$> xs)
w = maximum (length . xShow <$> xs)
in unlines $
in unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</lang>
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Proper divisors of [1..10]:
<pre>Proper divisors of [1..10]:
Line 3,117: Line 3,117:
So, borrowing from [[Factors of an integer#J|the J implementation]] of that related task:
So, borrowing from [[Factors of an integer#J|the J implementation]] of that related task:


<lang J>factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__
<syntaxhighlight lang="j">factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__
properDivisors=: factors -. ]</lang>
properDivisors=: factors -. ]</syntaxhighlight>


Proper divisors of numbers 1 through 10:
Proper divisors of numbers 1 through 10:


<lang J> (,&": ' -- ' ,&": properDivisors)&>1+i.10
<syntaxhighlight lang="j"> (,&": ' -- ' ,&": properDivisors)&>1+i.10
1 --
1 --
2 -- 1
2 -- 1
Line 3,132: Line 3,132:
8 -- 1 2 4
8 -- 1 2 4
9 -- 1 3
9 -- 1 3
10 -- 1 2 5</lang>
10 -- 1 2 5</syntaxhighlight>


Number(s) not exceeding 20000 with largest number of proper divisors (and the count of those divisors):
Number(s) not exceeding 20000 with largest number of proper divisors (and the count of those divisors):


<lang J> (, #@properDivisors)&> 1+I.(= >./) #@properDivisors@> 1+i.20000
<syntaxhighlight lang="j"> (, #@properDivisors)&> 1+I.(= >./) #@properDivisors@> 1+i.20000
15120 79
15120 79
18480 79</lang>
18480 79</syntaxhighlight>


Note that it's a bit more efficient to simply count factors here, when selecting the candidate numbers.
Note that it's a bit more efficient to simply count factors here, when selecting the candidate numbers.


<lang J> (, #@properDivisors)&> 1+I.(= >./) #@factors@> 1+i.20000
<syntaxhighlight lang="j"> (, #@properDivisors)&> 1+I.(= >./) #@factors@> 1+i.20000
15120 79
15120 79
18480 79</lang>
18480 79</syntaxhighlight>


We could also arbitrarily toss either 15120 or 18480 (keeping the other number), if it were important that we produce only one result.
We could also arbitrarily toss either 15120 or 18480 (keeping the other number), if it were important that we produce only one result.
Line 3,150: Line 3,150:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>import java.util.Collections;
<syntaxhighlight lang="java5">import java.util.Collections;
import java.util.LinkedList;
import java.util.LinkedList;
import java.util.List;
import java.util.List;
Line 3,182: Line 3,182:
System.out.println(x + ": " + count);
System.out.println(x + ": " + count);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1: []
<pre>1: []
Line 3,200: Line 3,200:
===ES5===
===ES5===


<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {


// Proper divisors
// Proper divisors
Line 3,268: Line 3,268:
);
);


})();</lang>
})();</syntaxhighlight>


{{out}}
{{out}}
Line 3,303: Line 3,303:
===ES6===
===ES6===


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 3,412: Line 3,412:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Proper divisors of [1..10]:
<pre>Proper divisors of [1..10]:
Line 3,432: Line 3,432:
{{works with|jq|1.4}}
{{works with|jq|1.4}}
In the following, proper_divisors returns a stream. In order to count the number of items in the stream economically, we first define "count(stream)":
In the following, proper_divisors returns a stream. In order to count the number of items in the stream economically, we first define "count(stream)":
<lang jq>def count(stream): reduce stream as $i (0; . + 1);
<syntaxhighlight lang="jq">def count(stream): reduce stream as $i (0; . + 1);


# unordered
# unordered
Line 3,452: Line 3,452:
( [null, 0];
( [null, 0];
count( $i | proper_divisors ) as $count
count( $i | proper_divisors ) as $count
| if $count > .[1] then [$i, $count] else . end);</lang>
| if $count > .[1] then [$i, $count] else . end);</syntaxhighlight>
'''The tasks:'''
'''The tasks:'''
<lang jq>"The proper divisors of the numbers 1 to 10 inclusive are:",
<syntaxhighlight lang="jq">"The proper divisors of the numbers 1 to 10 inclusive are:",
(range(1;11) as $i | "\($i): \( [ $i | proper_divisors] )"),
(range(1;11) as $i | "\($i): \( [ $i | proper_divisors] )"),
"",
"",
Line 3,460: Line 3,460:
"the maximal number proper divisors together with the corresponding",
"the maximal number proper divisors together with the corresponding",
"count of proper divisors is:",
"count of proper divisors is:",
most_proper_divisors(20000) </lang>
most_proper_divisors(20000) </syntaxhighlight>
{{out}}
{{out}}
<lang sh>$ jq -n -c -r -f /Users/peter/jq/proper_divisors.jq
<syntaxhighlight lang="sh">$ jq -n -c -r -f /Users/peter/jq/proper_divisors.jq
The proper divisors of the numbers 1 to 10 inclusive are:
The proper divisors of the numbers 1 to 10 inclusive are:
1: []
1: []
Line 3,478: Line 3,478:
the maximal number proper divisors together with the corresponding
the maximal number proper divisors together with the corresponding
count of proper divisors is:
count of proper divisors is:
[15120,79]</lang>
[15120,79]</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Use <code>factor</code> to obtain the prime factorization of the target number. I adopted the argument handling style of <code>factor</code> in my <code>properdivisors</code> function.
Use <code>factor</code> to obtain the prime factorization of the target number. I adopted the argument handling style of <code>factor</code> in my <code>properdivisors</code> function.
<syntaxhighlight lang="julia">
<lang Julia>
function properdivisors{T<:Integer}(n::T)
function properdivisors{T<:Integer}(n::T)
0 < n || throw(ArgumentError("number to be factored must be ≥ 0, got $n"))
0 < n || throw(ArgumentError("number to be factored must be ≥ 0, got $n"))
Line 3,522: Line 3,522:


println(nlst, " have the maximum proper divisor count of ", maxdiv, ".")
println(nlst, " have the maximum proper divisor count of ", maxdiv, ".")
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,543: Line 3,543:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


fun listProperDivisors(limit: Int) {
fun listProperDivisors(limit: Int) {
Line 3,582: Line 3,582:
println("The following number(s) have the most proper divisors, namely " + maxCount + "\n")
println("The following number(s) have the most proper divisors, namely " + maxCount + "\n")
for (n in most) println(n)
for (n in most) println(n)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,609: Line 3,609:
{{trans|Go}}
{{trans|Go}}
{{works with|langur|0.10}}
{{works with|langur|0.10}}
<lang langur>val .getproper = f(.x) for[=[]] .i of .x \ 2 { if .x div .i: _for ~= [.i] }
<syntaxhighlight lang="langur">val .getproper = f(.x) for[=[]] .i of .x \ 2 { if .x div .i: _for ~= [.i] }
val .cntproper = f(.x) for[=0] .i of .x \ 2 { if .x div .i: _for += 1 }
val .cntproper = f(.x) for[=0] .i of .x \ 2 { if .x div .i: _for += 1 }


Line 3,635: Line 3,635:


writeln $"The following number(s) <= 20000 have the most proper divisors (\.max;)"
writeln $"The following number(s) <= 20000 have the most proper divisors (\.max;)"
writeln .most</lang>
writeln .most</syntaxhighlight>


{{out}}
{{out}}
Line 3,655: Line 3,655:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>-- Return a table of the proper divisors of n
<syntaxhighlight lang="lua">-- Return a table of the proper divisors of n
function propDivs (n)
function propDivs (n)
if n < 2 then return {} end
if n < 2 then return {} end
Line 3,686: Line 3,686:
end
end
end
end
print(answer .. " has " .. mostDivs .. " proper divisors.")</lang>
print(answer .. " has " .. mostDivs .. " proper divisors.")</syntaxhighlight>
{{out}}
{{out}}
<pre>1:
<pre>1:
Line 3,703: Line 3,703:


A Function that yields the proper divisors of an integer n:
A Function that yields the proper divisors of an integer n:
<lang Mathematica>ProperDivisors[n_Integer /; n > 0] := Most@Divisors@n;</lang>
<syntaxhighlight lang="mathematica">ProperDivisors[n_Integer /; n > 0] := Most@Divisors@n;</syntaxhighlight>


Proper divisors of n from 1 to 10:
Proper divisors of n from 1 to 10:
<lang Mathematica>Grid@Table[{n, ProperDivisors[n]}, {n, 1, 10}]</lang>
<syntaxhighlight lang="mathematica">Grid@Table[{n, ProperDivisors[n]}, {n, 1, 10}]</syntaxhighlight>
{{out}}
{{out}}
<pre>1 {}
<pre>1 {}
Line 3,720: Line 3,720:


The number with the most divisors between 1 and 20,000:
The number with the most divisors between 1 and 20,000:
<syntaxhighlight lang="mathematica">Fold[
<lang Mathematica>Fold[
Last[SortBy[{#1, {#2, Length@ProperDivisors[#2]}}, Last]] &,
Last[SortBy[{#1, {#2, Length@ProperDivisors[#2]}}, Last]] &,
{0, 0},
{0, 0},
Range[20000]]</lang>
Range[20000]]</syntaxhighlight>
{{out}}
{{out}}
<pre>{18480, 79}</pre>
<pre>{18480, 79}</pre>


An alternate way to find the number with the most divisors between 1 and 20,000:
An alternate way to find the number with the most divisors between 1 and 20,000:
<lang Mathematica>Last@SortBy[
<syntaxhighlight lang="mathematica">Last@SortBy[
Table[
Table[
{n, Length@ProperDivisors[n]},
{n, Length@ProperDivisors[n]},
{n, 1, 20000}],
{n, 1, 20000}],
Last]</lang>
Last]</syntaxhighlight>
{{out}}
{{out}}
<pre>{15120, 79}</pre>
<pre>{15120, 79}</pre>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang matlab>function D=pd(N)
<syntaxhighlight lang="matlab">function D=pd(N)
K=1:ceil(N/2);
K=1:ceil(N/2);
D=K(~(rem(N, K)));</lang>
D=K(~(rem(N, K)));</syntaxhighlight>


{{out}}
{{out}}
Line 3,779: Line 3,779:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE ProperDivisors;
<syntaxhighlight lang="modula2">MODULE ProperDivisors;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 3,832: Line 3,832:


ReadChar
ReadChar
END ProperDivisors.</lang>
END ProperDivisors.</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
{{trans|C}}
{{trans|C}}
<lang nim>import strformat
<syntaxhighlight lang="nim">import strformat


proc properDivisors(n: int) =
proc properDivisors(n: int) =
Line 3,877: Line 3,877:
maxI = i
maxI = i


echo fmt"{maxI} with {max} divisors"</lang>
echo fmt"{maxI} with {max} divisors"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,894: Line 3,894:


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE ProperDivisors;
MODULE ProperDivisors;
IMPORT
IMPORT
Line 3,991: Line 3,991:
END
END
END ProperDivisors.
END ProperDivisors.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,011: Line 4,011:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>use Collection;
<syntaxhighlight lang="objeck">use Collection;


class Proper{
class Proper{
Line 4,054: Line 4,054:
}
}
}
}
</syntaxhighlight>
</lang>


Output:
Output:
Line 4,073: Line 4,073:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>Integer method: properDivs self 2 / seq filter(#[ self swap mod 0 == ]) }
<syntaxhighlight lang="oforth">Integer method: properDivs self 2 / seq filter(#[ self swap mod 0 == ]) }


10 seq apply(#[ dup print " : " print properDivs println ])
10 seq apply(#[ dup print " : " print properDivs println ])
20000 seq map(#[ dup properDivs size Pair new ]) reduce(#maxKey) println</lang>
20000 seq map(#[ dup properDivs size Pair new ]) reduce(#maxKey) println</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,093: Line 4,093:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>proper(n)=if(n==1, [], my(d=divisors(n)); d[2..#d]);
<syntaxhighlight lang="parigp">proper(n)=if(n==1, [], my(d=divisors(n)); d[2..#d]);
apply(proper, [1..10])
apply(proper, [1..10])
r=at=0; for(n=1,20000, t=numdiv(n); if(t>r, r=t; at=n)); [at, numdiv(t)-1]</lang>
r=at=0; for(n=1,20000, t=numdiv(n); if(t>r, r=t; at=n)); [at, numdiv(t)-1]</syntaxhighlight>
{{out}}
{{out}}
<pre>%1 = [[], [2], [3], [2, 4], [5], [2, 3, 6], [7], [2, 4, 8], [3, 9], [2, 5, 10]]
<pre>%1 = [[], [2], [3], [2, 4], [5], [2, 3, 6], [7], [2, 4, 8], [3, 9], [2, 5, 10]]
Line 4,103: Line 4,103:
{{works with|Free Pascal}}
{{works with|Free Pascal}}
Using prime factorisation
Using prime factorisation
<lang pascal>{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
<syntaxhighlight lang="pascal">{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
uses
sysutils;
sysutils;
Line 4,322: Line 4,322:
j := CntProperDivs(primeDecomp);
j := CntProperDivs(primeDecomp);
PrimeFacOut(primeDecomp);writeln(' ',j:10,' factors'); writeln;
PrimeFacOut(primeDecomp);writeln(' ',j:10,' factors'); writeln;
END.</lang>{{Output}}<pre>
END.</syntaxhighlight>{{Output}}<pre>
1 :
1 :
2 : 1
2 : 1
Line 4,343: Line 4,343:
===Using a module for divisors===
===Using a module for divisors===
{{libheader|ntheory}}
{{libheader|ntheory}}
<lang perl>use ntheory qw/divisors/;
<syntaxhighlight lang="perl">use ntheory qw/divisors/;
sub proper_divisors {
sub proper_divisors {
my $n = shift;
my $n = shift;
Line 4,365: Line 4,365:
no warnings 'numeric';
no warnings 'numeric';
say max(map { scalar(proper_divisors($_)) . " $_" } 1..20000);
say max(map { scalar(proper_divisors($_)) . " $_" } 1..20000);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1:
<pre>1:
Line 4,384: Line 4,384:
=={{header|Phix}}==
=={{header|Phix}}==
The factors routine is an auto-include. The actual implementation of it, from builtins\pfactors.e is
The factors routine is an auto-include. The actual implementation of it, from builtins\pfactors.e is
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">include1</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">include1</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
Line 4,416: Line 4,416:
<span style="color: #008080;">return</span> <span style="color: #000000;">lfactors</span> <span style="color: #0000FF;">&</span> <span style="color: #000000;">hfactors</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">lfactors</span> <span style="color: #0000FF;">&</span> <span style="color: #000000;">hfactors</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
The compiler knows where to find that, so the main program is just:
The compiler knows where to find that, so the main program is just:
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</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;">"%d: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</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>
<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;">"%d: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</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>
Line 4,437: Line 4,437:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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;">"%d divisors: %v\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">maxd</span><span style="color: #0000FF;">,</span><span style="color: #000000;">candidates</span><span style="color: #0000FF;">})</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;">"%d divisors: %v\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">maxd</span><span style="color: #0000FF;">,</span><span style="color: #000000;">candidates</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 4,455: Line 4,455:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
function ProperDivisors($n) {
function ProperDivisors($n) {
yield 1;
yield 1;
Line 4,492: Line 4,492:
echo "They have ", key($divisorsCount), " divisors.\n";
echo "They have ", key($divisorsCount), " divisors.\n";


</syntaxhighlight>
</lang>


Outputs:
Outputs:
Line 4,510: Line 4,510:


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
println(11111=proper_divisors(11111)),
println(11111=proper_divisors(11111)),
nl,
nl,
Line 4,549: Line 4,549:
println(maxN=MaxN),
println(maxN=MaxN),
println(maxLen=MaxLen),
println(maxLen=MaxLen),
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 4,570: Line 4,570:
===Larger tests===
===Larger tests===
Some larger tests of most number of divisors:
Some larger tests of most number of divisors:
<lang Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>
time(find_most_divisors(100_000)),
time(find_most_divisors(100_000)),
nl,
nl,
time(find_most_divisors(1_000_000)),
time(find_most_divisors(1_000_000)),
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 4,584: Line 4,584:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp># Generate all proper divisors.
<syntaxhighlight lang="picolisp"># Generate all proper divisors.
(de propdiv (N)
(de propdiv (N)
(head -1 (filter
(head -1 (filter
Line 4,593: Line 4,593:
(mapcar propdiv (range 1 10))
(mapcar propdiv (range 1 10))
# Output:
# Output:
# (NIL (1) (1) (1 2) (1) (1 2 3) (1) (1 2 4) (1 3) (1 2 5))</lang>
# (NIL (1) (1) (1 2) (1) (1 2 3) (1) (1 2 4) (1 3) (1 2 5))</syntaxhighlight>
===Brute-force===
===Brute-force===
<lang PicoLisp>(de propdiv (N)
<syntaxhighlight lang="picolisp">(de propdiv (N)
(cdr
(cdr
(rot
(rot
Line 4,615: Line 4,615:
(maxi
(maxi
countdiv
countdiv
(range 1 20000) ) )</lang>
(range 1 20000) ) )</syntaxhighlight>
===Factorization===
===Factorization===
<lang PicoLisp>(de accu1 (Var Key)
<syntaxhighlight lang="picolisp">(de accu1 (Var Key)
(if (assoc Key (val Var))
(if (assoc Key (val Var))
(con @ (inc (cdr @)))
(con @ (inc (cdr @)))
Line 4,640: Line 4,640:
factor
factor
(range 1 20000) )
(range 1 20000) )
@@ ) )</lang>
@@ ) )</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 4,648: Line 4,648:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>*process source xref;
<syntaxhighlight lang="pli">*process source xref;
(subrg):
(subrg):
cpd: Proc Options(main);
cpd: Proc Options(main);
Line 4,711: Line 4,711:
End;
End;


End;</lang>
End;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,731: Line 4,731:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
===version 1===
===version 1===
<syntaxhighlight lang="powershell">
<lang PowerShell>
function proper-divisor ($n) {
function proper-divisor ($n) {
if($n -ge 2) {
if($n -ge 2) {
Line 4,749: Line 4,749:
"$(proper-divisor 496)"
"$(proper-divisor 496)"
"$(proper-divisor 2048)"
"$(proper-divisor 2048)"
</syntaxhighlight>
</lang>


===version 2===
===version 2===
<syntaxhighlight lang="powershell">
<lang PowerShell>
function proper-divisor ($n) {
function proper-divisor ($n) {
if($n -ge 2) {
if($n -ge 2) {
Line 4,768: Line 4,768:
"$(proper-divisor 496)"
"$(proper-divisor 496)"
"$(proper-divisor 2048)"
"$(proper-divisor 2048)"
</syntaxhighlight>
</lang>


===version 3===
===version 3===
<syntaxhighlight lang="powershell">
<lang PowerShell>
function eratosthenes ($n) {
function eratosthenes ($n) {
if($n -gt 1){
if($n -gt 1){
Line 4,821: Line 4,821:
"$(proper-divisor 496)"
"$(proper-divisor 496)"
"$(proper-divisor 2048)"
"$(proper-divisor 2048)"
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 4,835: Line 4,835:
Taking a cue from [http://stackoverflow.com/a/171779 an SO answer]:
Taking a cue from [http://stackoverflow.com/a/171779 an SO answer]:


<lang prolog>divisor(N, Divisor) :-
<syntaxhighlight lang="prolog">divisor(N, Divisor) :-
UpperBound is round(sqrt(N)),
UpperBound is round(sqrt(N)),
between(1, UpperBound, D),
between(1, UpperBound, D),
Line 4,882: Line 4,882:
proper_divisor_count(N, Count) ),
proper_divisor_count(N, Count) ),
max(MaxCount, Num) ),
max(MaxCount, Num) ),
Result = (num(Num)-divisor_count(MaxCount)).</lang>
Result = (num(Num)-divisor_count(MaxCount)).</syntaxhighlight>


Output:
Output:


<lang prolog>?- show_proper_divisors_of_range(1,10).
<syntaxhighlight lang="prolog">?- show_proper_divisors_of_range(1,10).
2:[1]
2:[1]
3:[1]
3:[1]
Line 4,900: Line 4,900:
?- find_most_proper_divisors_in_range(1,20000,Result).
?- find_most_proper_divisors_in_range(1,20000,Result).
Result = num(15120)-divisor_count(79).
Result = num(15120)-divisor_count(79).
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
EnableExplicit


Line 4,960: Line 4,960:
CloseConsole()
CloseConsole()
EndIf
EndIf
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,983: Line 4,983:
===Python: Literal===
===Python: Literal===
A very literal interpretation
A very literal interpretation
<lang python>>>> def proper_divs2(n):
<syntaxhighlight lang="python">>>> def proper_divs2(n):
... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}
... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}
...
...
Line 4,994: Line 4,994:
>>> length
>>> length
79
79
>>> </lang>
>>> </syntaxhighlight>




Line 5,012: Line 5,012:


This version is over an order of magnitude faster for generating the proper divisors of the first 20,000 integers; at the expense of simplicity.
This version is over an order of magnitude faster for generating the proper divisors of the first 20,000 integers; at the expense of simplicity.
<lang python>from math import sqrt
<syntaxhighlight lang="python">from math import sqrt
from functools import lru_cache, reduce
from functools import lru_cache, reduce
from collections import Counter
from collections import Counter
Line 5,056: Line 5,056:
print([proper_divs(n) for n in range(1, 11)])
print([proper_divs(n) for n in range(1, 11)])
print(*max(((n, len(proper_divs(n))) for n in range(1, 20001)), key=lambda pd: pd[1]))</lang>
print(*max(((n, len(proper_divs(n))) for n in range(1, 20001)), key=lambda pd: pd[1]))</syntaxhighlight>


{{out}}
{{out}}
Line 5,066: Line 5,066:
Defining a list of proper divisors in terms of the prime factorization:
Defining a list of proper divisors in terms of the prime factorization:
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Proper divisors'''
<syntaxhighlight lang="python">'''Proper divisors'''


from itertools import accumulate, chain, groupby, product
from itertools import accumulate, chain, groupby, product
Line 5,179: Line 5,179:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Proper divisors of [1..10]:
<pre>Proper divisors of [1..10]:
Line 5,199: Line 5,199:
=== Python: The Simple Way ===
=== Python: The Simple Way ===
Not all the code submitters realized that it's a tie for the largest number of factors inside the limit. The task description clearly indicates only one answer is needed. But both numbers are provided for the curious. Also shown is the result for 25000, as there is no tie for that, just to show the program can handle either scenario.
Not all the code submitters realized that it's a tie for the largest number of factors inside the limit. The task description clearly indicates only one answer is needed. But both numbers are provided for the curious. Also shown is the result for 25000, as there is no tie for that, just to show the program can handle either scenario.
<lang python>def pd(num):
<syntaxhighlight lang="python">def pd(num):
factors = []
factors = []
for divisor in range(1,1+num//2):
for divisor in range(1,1+num//2):
Line 5,238: Line 5,238:
print()
print()
showcount(20000)
showcount(20000)
showcount(25000)</lang>
showcount(25000)</syntaxhighlight>
{{out}}
{{out}}
<pre style="white-space: pre-wrap;">There are no proper divisors of 1
<pre style="white-space: pre-wrap;">There are no proper divisors of 1
Line 5,260: Line 5,260:
<code>factors</code> is defined at [[Factors of an integer#Quackery]].
<code>factors</code> is defined at [[Factors of an integer#Quackery]].


<lang Quackery> [ factors -1 split drop ] is properdivisors ( n --> [ )
<syntaxhighlight lang="quackery"> [ factors -1 split drop ] is properdivisors ( n --> [ )


10 times [ i^ 1+ properdivisors echo cr ]
10 times [ i^ 1+ properdivisors echo cr ]
Line 5,271: Line 5,271:
else drop ]
else drop ]
swap echo say " has "
swap echo say " has "
echo say " proper divisors." cr</lang>
echo say " proper divisors." cr</syntaxhighlight>


{{out}}
{{out}}
Line 5,291: Line 5,291:
===Package solution===
===Package solution===
{{Works with|R|3.3.2 and above}}
{{Works with|R|3.3.2 and above}}
<lang rsplus># Proper divisors. 12/10/16 aev
<syntaxhighlight lang="rsplus"># Proper divisors. 12/10/16 aev
require(numbers);
require(numbers);
V <- sapply(1:20000, Sigma, k = 0, proper = TRUE); ind <- which(V==max(V));
V <- sapply(1:20000, Sigma, k = 0, proper = TRUE); ind <- which(V==max(V));
cat(" *** max number of divisors:", max(V), "\n"," *** for the following indices:",ind, "\n");</lang>
cat(" *** max number of divisors:", max(V), "\n"," *** for the following indices:",ind, "\n");</syntaxhighlight>


{{Output}}
{{Output}}
Line 5,303: Line 5,303:


===Filter solution===
===Filter solution===
<lang rsplus>#Task 1
<syntaxhighlight lang="rsplus">#Task 1
properDivisors <- function(N) Filter(function(x) N %% x == 0, seq_len(N %/% 2))
properDivisors <- function(N) Filter(function(x) N %% x == 0, seq_len(N %/% 2))


Line 5,323: Line 5,323:
" proper divisors.")
" proper divisors.")
}
}
mostProperDivisors(20000)</lang>
mostProperDivisors(20000)</syntaxhighlight>


{{Output}}
{{Output}}
Line 5,366: Line 5,366:
=== Short version ===
=== Short version ===


<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(require math)
(require math)
(define (proper-divisors n) (drop-right (divisors n) 1))
(define (proper-divisors n) (drop-right (divisors n) 1))
Line 5,376: Line 5,376:
(if (< (length (cdr best)) (length divs)) (cons n divs) best)))
(if (< (length (cdr best)) (length divs)) (cons n divs) best)))
(printf "~a has ~a proper divisors\n"
(printf "~a has ~a proper divisors\n"
(car most-under-20000) (length (cdr most-under-20000)))</lang>
(car most-under-20000) (length (cdr most-under-20000)))</syntaxhighlight>


{{out}}
{{out}}
Line 5,395: Line 5,395:


The '''main''' module will only be executed when this file is executed. When used as a library, it will not be used.
The '''main''' module will only be executed when this file is executed. When used as a library, it will not be used.
<lang racket>#lang racket/base
<syntaxhighlight lang="racket">#lang racket/base
(provide fold-divisors ; name as per "Abundant..."
(provide fold-divisors ; name as per "Abundant..."
proper-divisors)
proper-divisors)
Line 5,432: Line 5,432:
#:when [> c C])
#:when [> c C])
(values c i)))
(values c i)))
(printf "~a has ~a proper divisors\n" I C))</lang>
(printf "~a has ~a proper divisors\n" I C))</syntaxhighlight>


The output is the same as the short version above.
The output is the same as the short version above.
Line 5,442: Line 5,442:


There really isn't any point in using concurrency for a limit of 20_000. The setup and bookkeeping drowns out any benefit. Really doesn't start to pay off until the limit is 50_000 and higher. Try swapping in the commented out race map iterator line below for comparison.
There really isn't any point in using concurrency for a limit of 20_000. The setup and bookkeeping drowns out any benefit. Really doesn't start to pay off until the limit is 50_000 and higher. Try swapping in the commented out race map iterator line below for comparison.
<lang perl6>sub propdiv (\x) {
<syntaxhighlight lang="raku" line>sub propdiv (\x) {
my @l = 1 if x > 1;
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
(2 .. x.sqrt.floor).map: -> \d {
Line 5,460: Line 5,460:
}
}


say "max = {@candidates - 1}, candidates = {@candidates.tail}";</lang>
say "max = {@candidates - 1}, candidates = {@candidates.tail}";</syntaxhighlight>
{{out}}
{{out}}
<pre>1 []
<pre>1 []
Line 5,476: Line 5,476:
=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>
<syntaxhighlight lang="rexx">
/*REXX*/
/*REXX*/


Line 5,525: Line 5,525:
count_proper_divisors: Procedure
count_proper_divisors: Procedure
Parse Arg n
Parse Arg n
Return words(proper_divisors(n))</lang>
Return words(proper_divisors(n))</syntaxhighlight>
{{out}}
{{out}}
<pre>1 ->
<pre>1 ->
Line 5,551: Line 5,551:


With the (function) optimization, it's over &nbsp; '''20''' &nbsp; times faster.
With the (function) optimization, it's over &nbsp; '''20''' &nbsp; times faster.
<lang rexx>/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/
<syntaxhighlight lang="rexx">/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/
parse arg bot top inc range xtra /*obtain optional arguments from the CL*/
parse arg bot top inc range xtra /*obtain optional arguments from the CL*/
if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/
if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/
Line 5,592: Line 5,592:
/* [↓] adjust for a square. ___*/
/* [↓] adjust for a square. ___*/
if j*j==x then return a j b /*Was X a square? If so, add √ X */
if j*j==x then return a j b /*Was X a square? If so, add √ X */
return a b /*return the divisors (both lists). */</lang>
return a b /*return the divisors (both lists). */</syntaxhighlight>
{{out|output|text=&nbsp; when using the following input: &nbsp; <tt> 0 &nbsp; 10 &nbsp; 1 &nbsp; &nbsp; &nbsp; 20000 &nbsp; &nbsp; &nbsp; 166320 &nbsp; 1441440 &nbsp; 11796480000 </tt>}}
{{out|output|text=&nbsp; when using the following input: &nbsp; <tt> 0 &nbsp; 10 &nbsp; 1 &nbsp; &nbsp; &nbsp; 20000 &nbsp; &nbsp; &nbsp; 166320 &nbsp; 1441440 &nbsp; 11796480000 </tt>}}
<pre>
<pre>
Line 5,623: Line 5,623:


It accomplishes a faster speed by incorporating the calculation of an &nbsp; ''integer square root'' &nbsp; of an integer &nbsp; (without using any floating point arithmetic).
It accomplishes a faster speed by incorporating the calculation of an &nbsp; ''integer square root'' &nbsp; of an integer &nbsp; (without using any floating point arithmetic).
<lang rexx>/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/
<syntaxhighlight lang="rexx">/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/
parse arg bot top inc range xtra /*obtain optional arguments from the CL*/
parse arg bot top inc range xtra /*obtain optional arguments from the CL*/
if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/
if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/
Line 5,668: Line 5,668:
/* [↓] adjust for a square. ___*/
/* [↓] adjust for a square. ___*/
if j*j==x then return a j b /*Was X a square? If so, add √ X */
if j*j==x then return a j b /*Was X a square? If so, add √ X */
return a b /*return the divisors (both lists). */</lang>
return a b /*return the divisors (both lists). */</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 2<sup>nd</sup> REXX version when using the same inputs.}} <br><br>
{{out|output|text=&nbsp; is identical to the 2<sup>nd</sup> REXX version when using the same inputs.}} <br><br>


Line 5,675: Line 5,675:


For larger numbers, &nbsp; it is about &nbsp; '''7%''' &nbsp; faster.
For larger numbers, &nbsp; it is about &nbsp; '''7%''' &nbsp; faster.
<lang rexx>/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/
<syntaxhighlight lang="rexx">/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/
parse arg bot top inc range xtra /*obtain optional arguments from the CL*/
parse arg bot top inc range xtra /*obtain optional arguments from the CL*/
if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/
if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/
Line 5,727: Line 5,727:
end /*j*/
end /*j*/
if r*r==x then return a j b /*Was X a square? If so, add √ X */
if r*r==x then return a j b /*Was X a square? If so, add √ X */
return a b /*return proper divisors (both lists).*/</lang>
return a b /*return proper divisors (both lists).*/</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 2<sup>nd</sup> REXX version when using the same inputs.}} <br><br>
{{out|output|text=&nbsp; is identical to the 2<sup>nd</sup> REXX version when using the same inputs.}} <br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Proper divisors
# Project : Proper divisors


Line 5,748: Line 5,748:
see nl
see nl
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,764: Line 5,764:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>require "prime"
<syntaxhighlight lang="ruby">require "prime"


class Integer
class Integer
Line 5,781: Line 5,781:
select.each do |n|
select.each do |n|
puts "#{n} has #{size} divisors"
puts "#{n} has #{size} divisors"
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 5,800: Line 5,800:


===An Alternative Approach===
===An Alternative Approach===
<lang ruby>#Determine the integer within a range of integers that has the most proper divisors
<syntaxhighlight lang="ruby">#Determine the integer within a range of integers that has the most proper divisors
#Nigel Galloway: December 23rd., 2014
#Nigel Galloway: December 23rd., 2014
require "prime"
require "prime"
Line 5,806: Line 5,806:
(1..20000).each{|i| e = i.prime_division.inject(1){|n,g| n * (g[1]+1)}
(1..20000).each{|i| e = i.prime_division.inject(1){|n,g| n * (g[1]+1)}
n, g = e, i if e > n}
n, g = e, i if e > n}
puts "#{g} has #{n-1} proper divisors"</lang>
puts "#{g} has #{n-1} proper divisors"</syntaxhighlight>


{{out}}
{{out}}
Line 5,821: Line 5,821:
=={{header|Rust}}==
=={{header|Rust}}==


<lang rust>trait ProperDivisors {
<syntaxhighlight lang="rust">trait ProperDivisors {
fn proper_divisors(&self) -> Option<Vec<u64>>;
fn proper_divisors(&self) -> Option<Vec<u64>>;
}
}
Line 5,859: Line 5,859:
most_divisors.len());
most_divisors.len());
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Proper divisors of 1: []
<pre>Proper divisors of 1: []
Line 5,875: Line 5,875:


=={{header|S-BASIC}}==
=={{header|S-BASIC}}==
<syntaxhighlight lang="basic">
<lang Basic>
$lines
$lines


Line 5,939: Line 5,939:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,961: Line 5,961:


===Simple proper divisors===
===Simple proper divisors===
<lang Scala>def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
<syntaxhighlight lang="scala">def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
def format(i: Int, divisors: Seq[Int]) = f"$i%5d ${divisors.length}%2d ${divisors mkString " "}"
def format(i: Int, divisors: Seq[Int]) = f"$i%5d ${divisors.length}%2d ${divisors mkString " "}"


Line 5,973: Line 5,973:
}
}


list.foreach( number => println(f"$number%5d ${properDivisors(number).length}") )</lang>
list.foreach( number => println(f"$number%5d ${properDivisors(number).length}") )</syntaxhighlight>
{{out}}
{{out}}
<pre> n cnt PROPER DIVISORS
<pre> n cnt PROPER DIVISORS
Line 5,993: Line 5,993:
If ''Long''s are enough to you you can replace every ''BigInt'' with ''Long'' and the one ''BigInt(1)'' with ''1L''
If ''Long''s are enough to you you can replace every ''BigInt'' with ''Long'' and the one ''BigInt(1)'' with ''1L''


<lang Scala>import scala.annotation.tailrec
<syntaxhighlight lang="scala">import scala.annotation.tailrec


def factorize(x: BigInt): List[BigInt] = {
def factorize(x: BigInt): List[BigInt] = {
Line 6,010: Line 6,010:
val products = (1 until factors.length).flatMap(i => factors.combinations(i).map(_.product).toList).toList
val products = (1 until factors.length).flatMap(i => factors.combinations(i).map(_.product).toList).toList
(BigInt(1) :: products).filter(_ < n)
(BigInt(1) :: products).filter(_ < n)
}</lang>
}</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: writeProperDivisors (in integer: n) is func
const proc: writeProperDivisors (in integer: n) is func
Line 6,059: Line 6,059:
end for;
end for;
writeln(max_i <& " with " <& max <& " divisors");
writeln(max_i <& " with " <& max <& " divisors");
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 6,078: Line 6,078:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Raku}}
{{trans|Raku}}
<lang ruby>func propdiv (n) {
<syntaxhighlight lang="ruby">func propdiv (n) {
n.divisors.slice(0, -2)
n.divisors.slice(0, -2)
}
}
Line 6,096: Line 6,096:
}
}


say "max = #{max}, candidates = #{candidates}"</lang>
say "max = #{max}, candidates = #{candidates}"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,114: Line 6,114:
=={{header|Swift}}==
=={{header|Swift}}==
Simple function:
Simple function:
<lang Swift>func properDivs1(n: Int) -> [Int] {
<syntaxhighlight lang="swift">func properDivs1(n: Int) -> [Int] {


return filter (1 ..< n) { n % $0 == 0 }
return filter (1 ..< n) { n % $0 == 0 }
}</lang>
}</syntaxhighlight>
More efficient function:
More efficient function:
<lang Swift>import func Darwin.sqrt
<syntaxhighlight lang="swift">import func Darwin.sqrt


func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
Line 6,138: Line 6,138:
return sorted(result)
return sorted(result)
}</lang>
}</syntaxhighlight>
Rest of the task:
Rest of the task:
<lang Swift>for i in 1...10 {
<syntaxhighlight lang="swift">for i in 1...10 {
println("\(i): \(properDivs(i))")
println("\(i): \(properDivs(i))")
}
}
Line 6,152: Line 6,152:
}
}


println("\(num): \(max)")</lang>
println("\(num): \(max)")</syntaxhighlight>
{{out}}
{{out}}
<pre>1: []
<pre>1: []
Line 6,168: Line 6,168:


=={{header|tbas}}==
=={{header|tbas}}==
<syntaxhighlight lang="vb">
<lang vb>
dim _proper_divisors(100)
dim _proper_divisors(100)


Line 6,218: Line 6,218:
print "A maximum at ";
print "A maximum at ";
show_proper_divisors(maxindex, false)
show_proper_divisors(maxindex, false)
</syntaxhighlight>
</lang>
<pre>
<pre>
>tbas proper_divisors.bas
>tbas proper_divisors.bas
Line 6,241: Line 6,241:
Note that if a number, <math>k</math>, greater than 1 divides <math>n</math> exactly, both <math>k</math> and <math>n/k</math> are
Note that if a number, <math>k</math>, greater than 1 divides <math>n</math> exactly, both <math>k</math> and <math>n/k</math> are
proper divisors. (The raw answers are not sorted; the pretty-printer code sorts.)
proper divisors. (The raw answers are not sorted; the pretty-printer code sorts.)
<lang tcl>proc properDivisors {n} {
<syntaxhighlight lang="tcl">proc properDivisors {n} {
if {$n == 1} return
if {$n == 1} return
set divs 1
set divs 1
Line 6,266: Line 6,266:
}
}
}
}
puts "max: $maxI => (...$maxC…)"</lang>
puts "max: $maxI => (...$maxC…)"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,284: Line 6,284:
=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
{{trans|True BASIC}}
{{trans|True BASIC}}
<lang>LET m = 1
<syntaxhighlight lang="text">LET m = 1
LET c = 0
LET c = 0
Line 6,326: Line 6,326:
PRINT
PRINT
NEXT
NEXT
RETURN</lang>
RETURN</syntaxhighlight>
{{Out}}
{{Out}}
<pre>The proper divisors of the following numbers are:
<pre>The proper divisors of the following numbers are:
Line 6,345: Line 6,345:
0 OK, 0:415</pre>
0 OK, 0:415</pre>
=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public Sub Proper_Divisor()
<syntaxhighlight lang="vb">Public Sub Proper_Divisor()
Dim t() As Long, i As Long, l As Long, j As Long, c As Long
Dim t() As Long, i As Long, l As Long, j As Long, c As Long
For i = 1 To 10
For i = 1 To 10
Line 6,372: Line 6,372:
End If
End If
S = t
S = t
End Function</lang>
End Function</syntaxhighlight>
{{out}}
{{out}}
<pre>Proper divisor of 1 :
<pre>Proper divisor of 1 :
Line 6,389: Line 6,389:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Function ProperDivisors(number As Integer) As IEnumerable(Of Integer)
Function ProperDivisors(number As Integer) As IEnumerable(Of Integer)
Line 6,404: Line 6,404:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>1: {}
<pre>1: {}
Line 6,421: Line 6,421:
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
{{libheader|Wren-math}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt
import "/math" for Int
import "/math" for Int


Line 6,436: Line 6,436:
}
}
}
}
System.print("%(number) which has %(maxDivs) proper divisors.")</lang>
System.print("%(number) which has %(maxDivs) proper divisors.")</syntaxhighlight>


{{out}}
{{out}}
Line 6,456: Line 6,456:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>func PropDiv(N, Show); \Count and optionally show proper divisors of N
<syntaxhighlight lang="xpl0">func PropDiv(N, Show); \Count and optionally show proper divisors of N
int N, Show, D, C;
int N, Show, D, C;
[C:= 0;
[C:= 0;
Line 6,488: Line 6,488:
];
];
IntOut(0, SN); ChOut(0, ^ ); IntOut(0, Max); CrLf(0);
IntOut(0, SN); ChOut(0, ^ ); IntOut(0, Max); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 6,499: Line 6,499:
{{trans|D}}
{{trans|D}}
This is the simple version :
This is the simple version :
<lang zkl>fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) }</lang>
<syntaxhighlight lang="zkl">fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) }</syntaxhighlight>
This version is MUCH faster (the output isn't ordered however):
This version is MUCH faster (the output isn't ordered however):
<lang zkl>fcn properDivs(n){
<syntaxhighlight lang="zkl">fcn properDivs(n){
if(n==1) return(T);
if(n==1) return(T);
( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) )
( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) )
.pump(pd,'wrap(pd){ if(pd!=1 and (y:=n/pd)!=pd ) y else Void.Skip })
.pump(pd,'wrap(pd){ if(pd!=1 and (y:=n/pd)!=pd ) y else Void.Skip })
}</lang>
}</syntaxhighlight>


<lang zkl>[1..10].apply(properDivs).println();
<syntaxhighlight lang="zkl">[1..10].apply(properDivs).println();
[1..20_001].apply('wrap(n){ T(properDivs(n).len(),n) })
[1..20_001].apply('wrap(n){ T(properDivs(n).len(),n) })
.reduce(fcn([(a,_)]ab, [(c,_)]cd){ a>c and ab or cd },T(0,0))
.reduce(fcn([(a,_)]ab, [(c,_)]cd){ a>c and ab or cd },T(0,0))
.println();</lang>
.println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>