Practical numbers: Difference between revisions

Content added Content deleted
(Added 11l)
m (syntax highlighting fixup automation)
Line 22: Line 22:
{{trans|Nim}}
{{trans|Nim}}


<lang 11l>F properDivisors(n)
<syntaxhighlight lang="11l">F properDivisors(n)
V result = [1]
V result = [1]
L(i) 2 .. Int(sqrt(n))
L(i) 2 .. Int(sqrt(n))
Line 53: Line 53:
print(‘Found ’count‘ practical numbers between 1 and 333.’)
print(‘Found ’count‘ practical numbers between 1 and 333.’)
print()
print()
print(‘666 is ’(I isPractical(666) {‘’} E ‘not ’)‘a practical number.’)</lang>
print(‘666 is ’(I isPractical(666) {‘’} E ‘not ’)‘a practical number.’)</syntaxhighlight>


{{out}}
{{out}}
Line 71: Line 71:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang APL>pract ← ∧/⍳∊(+⌿⊢×[1](2/⍨≢)⊤(⍳2*≢))∘(⍸0=⍳|⊢)</lang>
<syntaxhighlight lang="apl">pract ← ∧/⍳∊(+⌿⊢×[1](2/⍨≢)⊤(⍳2*≢))∘(⍸0=⍳|⊢)</syntaxhighlight>
{{out}}
{{out}}
<lang APL> ⍸pract¨⍳333 ⍝ Which numbers from 1 to 333 are practical?
<syntaxhighlight lang="apl"> ⍸pract¨⍳333 ⍝ Which numbers from 1 to 333 are practical?
1 2 4 6 8 12 16 18 20 24 28 30 32 36 40 42 48 54 56 60 64 66 72 78 80 84 88 90 96 100 104 108 112 120 126 128 132 140 144
1 2 4 6 8 12 16 18 20 24 28 30 32 36 40 42 48 54 56 60 64 66 72 78 80 84 88 90 96 100 104 108 112 120 126 128 132 140 144
150 156 160 162 168 176 180 192 196 198 200 204 208 210 216 220 224 228 234 240 252 256 260 264 270 272 276 280 288
150 156 160 162 168 176 180 192 196 198 200 204 208 210 216 220 224 228 234 240 252 256 260 264 270 272 276 280 288
294 300 304 306 308 312 320 324 330
294 300 304 306 308 312 320 324 330
pract 666 ⍝ Is 666 practical?
pract 666 ⍝ Is 666 practical?
1</lang>
1</syntaxhighlight>


=={{header|C#|CSharp}}==
=={{header|C#|CSharp}}==
<lang csharp>using System.Collections.Generic; using System.Linq; using static System.Console;
<syntaxhighlight lang="csharp">using System.Collections.Generic; using System.Linq; using static System.Console;


class Program {
class Program {
Line 99: Line 99:
Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m);
Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m);
do Write("\n{0,5} is a{1}practical number.",
do Write("\n{0,5} is a{1}practical number.",
m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }</lang>
m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 2 4 6 8 12 16 18 20 24
<pre> 1 2 4 6 8 12 16 18 20 24
Line 117: Line 117:
=={{header|C++}}==
=={{header|C++}}==
{{trans|Phix}}
{{trans|Phix}}
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iostream>
#include <numeric>
#include <numeric>
Line 192: Line 192:
<< "a practical number.\n";
<< "a practical number.\n";
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 210: Line 210:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>sub make_divisors( n as uinteger, div() as uinteger )
<syntaxhighlight lang="freebasic">sub make_divisors( n as uinteger, div() as uinteger )
'produces a list of an integer's proper divisors
'produces a list of an integer's proper divisors
for i as uinteger = n/2 to 1 step -1
for i as uinteger = n/2 to 1 step -1
Line 255: Line 255:
for n as uinteger = 2 to 666
for n as uinteger = 2 to 666
if is_practical(n) then print n;" ";
if is_practical(n) then print n;" ";
next n:print</lang>
next n:print</syntaxhighlight>


All practical numbers up to and including the stretch goal of DCLXVI.
All practical numbers up to and including the stretch goal of DCLXVI.
Line 265: Line 265:
{{trans|Wren}}
{{trans|Wren}}
{{libheader|Go-rcu}}
{{libheader|Go-rcu}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 321: Line 321:
fmt.Println(" The final ten are", practical[len(practical)-10:])
fmt.Println(" The final ten are", practical[len(practical)-10:])
fmt.Println("\n666 is practical:", isPractical(666))
fmt.Println("\n666 is practical:", isPractical(666))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 337: Line 337:
Borrowed from the [[Proper divisors#J]] page:
Borrowed from the [[Proper divisors#J]] page:


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


Borrowed from the [[Power set#J]] page:
Borrowed from the [[Power set#J]] page:


<lang J>ps=: #~ 2 #:@i.@^ #</lang>
<syntaxhighlight lang="j">ps=: #~ 2 #:@i.@^ #</syntaxhighlight>


Implementation:
Implementation:


<lang J>isPrac=: ('' -:&# i. -. 0,+/"1@(ps ::empty)@properDivisors)"0</lang>
<syntaxhighlight lang="j">isPrac=: ('' -:&# i. -. 0,+/"1@(ps ::empty)@properDivisors)"0</syntaxhighlight>


Task examples:
Task examples:


<lang J> +/ isPrac 1+i.333 NB. count practical numbers
<syntaxhighlight lang="j"> +/ isPrac 1+i.333 NB. count practical numbers
77
77
(#~ isPrac) 1+i.333 NB. list them
(#~ isPrac) 1+i.333 NB. list them
1 2 4 6 8 12 16 18 20 24 28 30 32 36 40 42 48 54 56 60 64 66 72 78 80 84 88 90 96 100 104 108 112 120 126 128 132 140 144 150 156 160 162 168 176 180 192 196 198 200 204 208 210 216 220 224 228 234 240 252 256 260 264 270 272 276 280 288 294 300 304 306 30...
1 2 4 6 8 12 16 18 20 24 28 30 32 36 40 42 48 54 56 60 64 66 72 78 80 84 88 90 96 100 104 108 112 120 126 128 132 140 144 150 156 160 162 168 176 180 192 196 198 200 204 208 210 216 220 224 228 234 240 252 256 260 264 270 272 276 280 288 294 300 304 306 30...
isPrac 666 NB. test
isPrac 666 NB. test
1</lang>
1</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{trans|Phix}}
{{trans|Phix}}
<lang java>import java.util.*;
<syntaxhighlight lang="java">import java.util.*;


public class PracticalNumbers {
public class PracticalNumbers {
Line 455: Line 455:
return str.toString();
return str.toString();
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 479: Line 479:
The version of `proper_divisors` at [[Proper_divisors#jq]] may be used and therefore its definition
The version of `proper_divisors` at [[Proper_divisors#jq]] may be used and therefore its definition
is not repeated here.
is not repeated here.
<lang jq># A reminder to include the definition of `proper_divisors`
<syntaxhighlight lang="jq"># A reminder to include the definition of `proper_divisors`
# include "proper_divisors" { search: "." };
# include "proper_divisors" { search: "." };


Line 532: Line 532:
task(333),
task(333),
(666,6666,66666
(666,6666,66666
| "\nIs \(.) practical? \(if isPractical then "Yes." else "No." end)" )</lang>
| "\nIs \(.) practical? \(if isPractical then "Yes." else "No." end)" )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 550: Line 550:
=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Python}}
{{trans|Python}}
<lang julia>using Primes
<syntaxhighlight lang="julia">using Primes


""" proper divisors of n """
""" proper divisors of n """
Line 586: Line 586:
println("$n is ", ispractical(n) ? "" : "not ", "a practical number.")
println("$n is ", ispractical(n) ? "" : "not ", "a practical number.")
end
end
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
There are 77 practical numbers between 1 to 333 inclusive.
There are 77 practical numbers between 1 to 333 inclusive.
Line 598: Line 598:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import intsets, math, sequtils, strutils
<syntaxhighlight lang="nim">import intsets, math, sequtils, strutils


func properDivisors(n: int): seq[int] =
func properDivisors(n: int): seq[int] =
Line 627: Line 627:
echo "Found ", count, " practical numbers between 1 and 333."
echo "Found ", count, " practical numbers between 1 and 333."
echo()
echo()
echo "666 is ", if 666.isPractical: "" else: "not ", "a practical number."</lang>
echo "666 is ", if 666.isPractical: "" else: "not ", "a practical number."</syntaxhighlight>


{{out}}
{{out}}
Line 648: Line 648:
because the inequality above holds for each of its prime factors:
because the inequality above holds for each of its prime factors:
3 ≤ σ(2) + 1 = 4, 29 ≤ σ(2 × 3^2) + 1 = 40, and 823 ≤ σ(2 × 3^2 × 29) + 1 = 1171. </pre>
3 ≤ σ(2) + 1 = 4, 29 ≤ σ(2 × 3^2) + 1 = 40, and 823 ≤ σ(2 × 3^2 × 29) + 1 = 1171. </pre>
<lang pascal>program practicalnumbers;
<syntaxhighlight lang="pascal">program practicalnumbers;
{$IFDEF FPC}
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
Line 838: Line 838:
{$IFNDEF UNIX} readln; {$ENDIF}
{$IFNDEF UNIX} readln; {$ENDIF}
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> TIO.RUN.
<pre> TIO.RUN.
Line 871: Line 871:
==={{header|alternative}}===
==={{header|alternative}}===
Now without generating sum of allset.
Now without generating sum of allset.
<lang pascal>program practicalnumbers2;
<syntaxhighlight lang="pascal">program practicalnumbers2;


{$IFDEF FPC}
{$IFDEF FPC}
Line 1,003: Line 1,003:
{$ENDIF}
{$ENDIF}
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> TIO.RUN
<pre> TIO.RUN
Line 1,030: Line 1,030:
=={{header|Perl}}==
=={{header|Perl}}==
{{libheader|ntheory}}
{{libheader|ntheory}}
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use feature 'say';
use feature 'say';
Line 1,057: Line 1,057:
say @pn . " matching numbers:\n" . (sprintf "@{['%4d' x @pn]}", @pn) =~ s/(.{40})/$1\n/gr;
say @pn . " matching numbers:\n" . (sprintf "@{['%4d' x @pn]}", @pn) =~ s/(.{40})/$1\n/gr;
say '';
say '';
printf "%6d is practical? %s\n", $_, is_practical($_) ? 'True' : 'False' for 666, 6666, 66666;</lang>
printf "%6d is practical? %s\n", $_, is_practical($_) ? 'True' : 'False' for 666, 6666, 66666;</syntaxhighlight>
{{out}}
{{out}}
<pre>77 matching numbers:
<pre>77 matching numbers:
Line 1,074: Line 1,074:
=={{header|Phix}}==
=={{header|Phix}}==
{{trans|Python|(the composition of functions version)}}
{{trans|Python|(the composition of functions version)}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">sum_of_any_subset</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;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">sum_of_any_subset</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;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- return true if any subset of f sums to n.</span>
<span style="color: #000080;font-style:italic;">-- return true if any subset of f sums to n.</span>
Line 1,103: Line 1,103:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">666</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6666</span><span style="color: #0000FF;">,</span><span style="color: #000000;">66666</span><span style="color: #0000FF;">,</span><span style="color: #000000;">672</span><span style="color: #0000FF;">,</span><span style="color: #000000;">720</span><span style="color: #0000FF;">},</span><span style="color: #000000;">stretch</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">666</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6666</span><span style="color: #0000FF;">,</span><span style="color: #000000;">66666</span><span style="color: #0000FF;">,</span><span style="color: #000000;">672</span><span style="color: #0000FF;">,</span><span style="color: #000000;">720</span><span style="color: #0000FF;">},</span><span style="color: #000000;">stretch</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,119: Line 1,119:
===Python: Straight forward implementation===
===Python: Straight forward implementation===


<lang python>from itertools import chain, cycle, accumulate, combinations
<syntaxhighlight lang="python">from itertools import chain, cycle, accumulate, combinations
from typing import List, Tuple
from typing import List, Tuple


Line 1,174: Line 1,174:
print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])
print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])
x = 666
x = 666
print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")</lang>
print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")</syntaxhighlight>


{{out}}
{{out}}
Line 1,192: Line 1,192:
An extra check on the sum of all factors has a minor positive effect too.
An extra check on the sum of all factors has a minor positive effect too.


<lang python>def is_practical5(x: int) -> bool:
<syntaxhighlight lang="python">def is_practical5(x: int) -> bool:
"""Practical number test with factor reverse sort and short-circuiting."""
"""Practical number test with factor reverse sort and short-circuiting."""


Line 1,229: Line 1,229:
print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
x = 5184
x = 5184
print(f"\nEXTRA GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")</lang>
print(f"\nEXTRA GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")</syntaxhighlight>


{{out}}
{{out}}
Line 1,250: Line 1,250:
===Composition of pure functions===
===Composition of pure functions===


<lang python>'''Practical numbers'''
<syntaxhighlight lang="python">'''Practical numbers'''


from itertools import accumulate, chain, groupby, product
from itertools import accumulate, chain, groupby, product
Line 1,417: Line 1,417:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>77 OEIS A005153 numbers in [1..333]
<pre>77 OEIS A005153 numbers in [1..333]
Line 1,434: Line 1,434:


=={{header|Raku}}==
=={{header|Raku}}==
<lang perl6>use Prime::Factor:ver<0.3.0+>;
<syntaxhighlight lang="raku" line>use Prime::Factor:ver<0.3.0+>;


sub is-practical ($n) {
sub is-practical ($n) {
Line 1,448: Line 1,448:
given [ (1..333).hyper(:32batch).grep: { is-practical($_) } ];
given [ (1..333).hyper(:32batch).grep: { is-practical($_) } ];


printf "%5s is practical? %s\n", $_, .&is-practical for 666, 6666, 66666, 672, 720;</lang>
printf "%5s is practical? %s\n", $_, .&is-practical for 666, 6666, 66666, 672, 720;</syntaxhighlight>
{{out}}
{{out}}
<pre>77 matching numbers:
<pre>77 matching numbers:
Line 1,468: Line 1,468:
=={{header|Rust}}==
=={{header|Rust}}==
{{trans|Phix}}
{{trans|Phix}}
<lang rust>fn sum_of_any_subset(n: isize, f: &[isize]) -> bool {
<syntaxhighlight lang="rust">fn sum_of_any_subset(n: isize, f: &[isize]) -> bool {
let len = f.len();
let len = f.len();
if len == 0 {
if len == 0 {
Line 1,571: Line 1,571:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,587: Line 1,587:
=={{header|Sidef}}==
=={{header|Sidef}}==
Built-in:
Built-in:
<lang ruby>say is_practical(2**128 + 1) #=> false
<syntaxhighlight lang="ruby">say is_practical(2**128 + 1) #=> false
say is_practical(2**128 + 4) #=> true</lang>
say is_practical(2**128 + 4) #=> true</syntaxhighlight>


Slow implementation (as the task requires):
Slow implementation (as the task requires):
<lang ruby>func is_practical(n) {
<syntaxhighlight lang="ruby">func is_practical(n) {


var set = Set()
var set = Set()
Line 1,612: Line 1,612:
for n in ([666, 6666, 66666]) {
for n in ([666, 6666, 66666]) {
say "#{'%5s' % n } is practical? #{is_practical(n)}"
say "#{'%5s' % n } is practical? #{is_practical(n)}"
}</lang>
}</syntaxhighlight>


Efficient algorithm:
Efficient algorithm:
<lang ruby>func is_practical(n) {
<syntaxhighlight lang="ruby">func is_practical(n) {


n.is_odd && return (n == 1)
n.is_odd && return (n == 1)
Line 1,629: Line 1,629:


return true
return true
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,642: Line 1,642:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Imports System.Collections.Generic, System.Linq, System.Console
<syntaxhighlight lang="vbnet">Imports System.Collections.Generic, System.Linq, System.Console


Module Module1
Module Module1
Line 1,667: Line 1,667:
Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4
Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
Same as C#
Same as C#
Line 1,673: Line 1,673:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-math}}
<lang ecmascript>import "/math" for Int, Nums
<syntaxhighlight lang="ecmascript">import "/math" for Int, Nums


var powerset // recursive
var powerset // recursive
Line 1,710: Line 1,710:
System.print(" The first ten are %(practical[0..9])")
System.print(" The first ten are %(practical[0..9])")
System.print(" The final ten are %(practical[-10..-1])")
System.print(" The final ten are %(practical[-10..-1])")
System.print("\n666 is practical: %(isPractical.call(666))")</lang>
System.print("\n666 is practical: %(isPractical.call(666))")</syntaxhighlight>


{{out}}
{{out}}