Product of divisors
Given a positive integer, return the product of its positive divisors.
- Task
Show the result for the first 50 positive integers.
11l
<lang 11l>F product_of_divisors(n)
V ans = 1 V i = 1 V j = 1 L i * i <= n I 0 == n % i ans *= i j = n I/ i I j != i ans *= j i++ R ans
print((1..50).map(n -> product_of_divisors(n)))</lang>
- Output:
[1, 2, 3, 8, 5, 36, 7, 64, 27, 100, 11, 1728, 13, 196, 225, 1024, 17, 5832, 19, 8000, 441, 484, 23, 331776, 125, 676, 729, 21952, 29, 810000, 31, 32768, 1089, 1156, 1225, 10077696, 37, 1444, 1521, 2560000, 41, 3111696, 43, 85184, 91125, 2116, 47, 254803968, 343, 125000]
ALGOL 68
<lang algol68>BEGIN # find the product of the divisors of the first 100 positive integers #
# calculates the number of divisors of v # PROC divisor count = ( INT v )INT: BEGIN INT total := 1, n := v; # Deal with powers of 2 first # WHILE NOT ODD n DO total +:= 1; n OVERAB 2 OD; # Odd prime factors up to the square root # INT p := 3; WHILE ( p * p ) <= n DO INT count := 1; WHILE n MOD p = 0 DO count +:= 1; n OVERAB p OD; p +:= 2; total *:= count OD; # If n > 1 then it's prime # IF n > 1 THEN total *:= 2 FI; total END # divisor count #; # calculates the product of the divisors of v # PROC divisor product = ( INT v )LONG INT: BEGIN INT count = divisor count( v ); LONG INT product := v ^ ( count OVER 2 ); IF ODD count THEN product *:= ENTIER sqrt( v ) FI; product END # divisor product # ; BEGIN INT limit = 50; print( ( "Product of divisors for the first ", whole( limit, 0 ), " positive integers:", newline ) ); FOR n TO limit DO print( ( whole( divisor product( n ), -10 ) ) ); IF n MOD 5 = 0 THEN print( ( newline ) ) FI OD END
END</lang>
- Output:
Product of divisors for the first 50 positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
ALGOL W
<lang algolw>begin % find the product of the divisors of the first 100 positive integers %
% calculates the number of divisors of v % integer procedure divisor_count( integer value v ) ; begin integer total, n, p; total := 1; n := v; % Deal with powers of 2 first % while not odd( n ) do begin total := total + 1; n := n div 2 end while_not_odd_n ; % Odd prime factors up to the square root % p := 3; while ( p * p ) <= n do begin integer count; count := 1; while n rem p = 0 do begin count := count + 1; n := n div p end while_n_rem_p_eq_0 ; p := p + 2; total := total * count end while_p_x_p_le_n ; % If n > 1 then it's prime % if n > 1 then total := total * 2; total end divisor_count ; % calculates the product of the divisors of v % integer procedure divisor_product( integer value v ) ; begin integer count, product; count := divisor_count( v ); product := 1; for i := 1 until count div 2 do product := product * v; if odd( count ) then product := product * entier( sqrt( v ) ); product end divisor_product ; begin integer limit; limit := 50; write( i_w := 1, s_w := 0, "Product of divisors for the first ", limit, " positive integers:" ); for n := 1 until limit do begin if n rem 5 = 1 then write(); writeon( i_w := 10, s_w := 1, divisor_product( n ) ) end for_n end
end.</lang>
- Output:
Product of divisors for the first 50 positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
APL
<lang APL>divprod ← ×/(⍸0=⍳|⊢) 10 5 ⍴ divprod¨ ⍳50</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Arturo
<lang rebol>loop split.every:5 to [:string] map 1..50 => [product factors] 'line [
print map line 'i -> pad i 10
]</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
AWK
<lang AWK>
- syntax: GAWK -f PRODUCT_OF_DIVISORS.AWK
- converted from Go
BEGIN {
limit = 50 printf("The products of positive divisors for the first %d positive integers are:\n",limit) for (i=1; i<=limit; i++) { printf("%12d ",product_divisors(i)) if (i % 10 == 0) { printf("\n") } } exit(0)
} function product_divisors(n, ans,i,j,k) {
ans = 1 i = 1 k = (n % 2 == 0) ? 1 : 2 while (i*i <= n) { if (n % i == 0) { ans *= i j = n / i if (j != i) { ans *= j } } i += k } return(ans)
} </lang>
- Output:
The products of positive divisors for the first 50 positive integers are: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
BASIC
<lang basic>10 N = 50 20 DIM D(N) 30 FOR I=1 TO N: D(I)=1: NEXT 40 FOR I=2 TO N 50 FOR J=I TO N STEP I 60 D(J) = D(J)*I 70 NEXT J 80 NEXT I 90 FOR I=1 TO N: PRINT D(I),: NEXT</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 1.00777E+07 37 1444 1521 2.56E+06 41 3.1117E+06 43 85184 91125 2116 47 2.54804E+08 343 125000
C
<lang c>#include <math.h>
- include <stdio.h>
// See https://en.wikipedia.org/wiki/Divisor_function unsigned int divisor_count(unsigned int n) {
unsigned int total = 1; unsigned int p;
// Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) { ++total; } // Odd prime factors up to the square root for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } // If n > 1 then it's prime if (n > 1) { total *= 2; } return total;
}
// See https://mathworld.wolfram.com/DivisorProduct.html unsigned int divisor_product(unsigned int n) {
return pow(n, divisor_count(n) / 2.0);
}
int main() {
const unsigned int limit = 50; unsigned int n;
printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } }
return 0;
}</lang>
- Output:
Product of divisors for the first 50 positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
C++
<lang cpp>#include <cmath>
- include <iomanip>
- include <iostream>
// See https://en.wikipedia.org/wiki/Divisor_function unsigned int divisor_count(unsigned int n) {
unsigned int total = 1; // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) ++total; // Odd prime factors up to the square root for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } // If n > 1 then it's prime if (n > 1) total *= 2; return total;
}
// See https://mathworld.wolfram.com/DivisorProduct.html unsigned int divisor_product(unsigned int n) {
return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));
}
int main() {
const unsigned int limit = 50; std::cout << "Product of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(11) << divisor_product(n); if (n % 5 == 0) std::cout << '\n'; }
}</lang>
- Output:
Product of divisors for the first 50 positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Common Lisp
<lang Lisp> (format t "~{~a ~}~%"
(loop for a from 1 to 100 collect (loop with z = 1 for b from 1 to a when (zerop (rem a b)) do (setf z (* z b)) finally (return z))))
</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000 2601 140608 53 8503056 3025 9834496 3249 3364 59 46656000000 61 3844 250047 2097152 4225 18974736 67 314432 4761 24010000 71 139314069504 73 5476 421875 438976 5929 37015056 79 3276800000 59049 6724 83 351298031616 7225 7396 7569 59969536 89 531441000000 8281 778688 8649 8836 9025 782757789696 97 941192 970299 1000000000
Cowgol
<lang cowgol>include "cowgol.coh";
sub divprod(n: uint32): (prod: uint32) is
prod := 1; var d := n; while d > 1 loop if n % d == 0 then prod := prod * d; end if; d := d - 1; end loop;
end sub;
var n: uint32 := 1; while n <= 50 loop
var dp := divprod(n); print_i32(dp); print_char('\t'); if dp < 10000000 then print_char('\t'); end if; if n % 5 == 0 then print_nl(); end if; n := n + 1;
end loop;</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
D
<lang d>import std.math; import std.stdio;
// See https://en.wikipedia.org/wiki/Divisor_function uint divisorCount(uint n) {
uint total = 1; // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) { total++; } // Odd prime factors up to the square root for (uint p = 3; p * p <= n; p += 2) { uint count = 1; for (; n % p == 0; n /= p) { count++; } total *= count; } // If n > 1 then it's prime if (n > 1) { total *= 2; } return total;
}
uint divisorProduct(uint n) {
return cast(uint) pow(n, divisorCount(n) / 2.0);
}
void main() {
immutable limit = 50; writeln("Product of divisors for the first ", limit, "positive integers:"); for (uint n = 1; n <= limit; n++) { writef("%11d", divisorProduct(n)); if (n % 5 == 0) { writeln; } }
}</lang>
- Output:
Product of divisors for the first 50positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 124 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Factor
<lang factor>USING: grouping io math.primes.factors math.ranges prettyprint sequences ;
"Product of divisors for the first 50 positive integers:" print 50 [1,b] [ divisors product ] map 5 group simple-table.</lang>
- Output:
Product of divisors for the first 50 positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Fortran
<lang fortran> program divprod
implicit none integer divis(50), i, j do 10 i=1, 50 10 divis(i) = 1 do 20 i=1, 50 do 20 j=i, 50, i 20 divis(j) = divis(j)*i do 30 i=1, 50 write (*,'(I10)',advance='no') divis(i) 30 if (i/5 .ne. (i-1)/5) write (*,*) end program</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
FreeBASIC
<lang freebasic>dim p as ulongint for n as uinteger = 1 to 50
p = n for i as uinteger = 2 to n/2 if n mod i = 0 then p *= i next i print p,
next n </lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968
Go
<lang go>package main
import "fmt"
func prodDivisors(n int) int {
prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod
}
func main() {
fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } }
}</lang>
- Output:
The products of positive divisors for the first 50 positive integers are: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
GW-BASIC
<lang gwbasic> 10 FOR N = 1 TO 50 20 P# = N 30 FOR I = 2 TO INT(N/2) 40 IF N MOD I = 0 THEN P# = P# * I 50 NEXT I 60 PRINT P#, 70 NEXT N</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Haskell
<lang haskell>import Data.List.Split (chunksOf)
DIVISORS -----------------------
divisors :: Integral a => a -> [a] divisors n =
((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id
SUMS AND PRODUCTS OF DIVISORS -------------
main :: IO () main =
mapM_ putStrLn [ "Sums of divisors of [1..100]:", test sum, "Products of divisors of [1..100]:", test product ]
test :: (Show a, Integral a) => ([a] -> a) -> String test f =
let xs = show . f . divisors <$> [1 .. 100] w = maximum $ length <$> xs in unlines $ unwords <$> fmap (fmap (justifyRight w ' ')) (chunksOf 5 xs)
justifyRight :: Int -> Char -> String -> String justifyRight n c = (drop . length) <*> (replicate n c <>)</lang>
- Output:
Sums of divisors of [1..100]: 1 3 4 7 6 12 8 15 13 18 12 28 14 24 24 31 18 39 20 42 32 36 24 60 31 42 40 56 30 72 32 63 48 54 48 91 38 60 56 90 42 96 44 84 78 72 48 124 57 93 72 98 54 120 72 120 80 90 60 168 62 96 104 127 84 144 68 126 96 144 72 195 74 114 124 140 96 168 80 186 121 126 84 224 108 132 120 180 90 234 112 168 128 144 120 252 98 171 156 217 Products of divisors of [1..100]: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000 2601 140608 53 8503056 3025 9834496 3249 3364 59 46656000000 61 3844 250047 2097152 4225 18974736 67 314432 4761 24010000 71 139314069504 73 5476 421875 438976 5929 37015056 79 3276800000 59049 6724 83 351298031616 7225 7396 7569 59969536 89 531441000000 8281 778688 8649 8836 9025 782757789696 97 941192 970299 1000000000
Java
<lang java>public class ProductOfDivisors {
private static long divisorCount(long n) { long total = 1; // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) { ++total; } // Odd prime factors up to the square root for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } // If n > 1 then it's prime if (n > 1) { total *= 2; } return total; }
private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); }
public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } }
}</lang>
- Output:
Product of divisors for the first 50 positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
jq
Works with gojq, the Go implementation of jq
gojq should be used if integer precision is to be guaranteed.
Since a `divisors` function is more likely to be generally useful than a "product of divisors" function, this entry implements the latter in terms of the former, without any appreciable cost because a streaming approach is used. <lang jq># divisors as an unsorted stream def divisors:
if . == 1 then 1 else . as $n | label $out | range(1; $n) as $i | ($i * $i) as $i2 | if $i2 > $n then break $out else if $i2 == $n then $i elif ($n % $i) == 0 then $i, ($n/$i) else empty
end
end end;
def product(s): reduce s as $x (1; . * $x);
def product_of_divisors: product(divisors);
- For pretty-printing
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; </lang> Example <lang jq>"n product of divisors", (range(1; 51) | "\(lpad(3)) \(product_of_divisors|lpad(15))")</lang>
- Output:
n product of divisors 1 1 2 2 3 3 4 8 5 5 6 36 7 7 8 64 9 27 10 100 11 11 12 1728 13 13 14 196 15 225 16 1024 17 17 18 5832 19 19 20 8000 21 441 22 484 23 23 24 331776 25 125 26 676 27 729 28 21952 29 29 30 810000 31 31 32 32768 33 1089 34 1156 35 1225 36 10077696 37 37 38 1444 39 1521 40 2560000 41 41 42 3111696 43 43 44 85184 45 91125 46 2116 47 47 48 254803968 49 343 50 125000
Example illustrating the use of gojq <lang jq>1234567890 | [., product_of_divisors] </lang>
- Output:
[1234567890,157166308290967624614434966485493540963726721698403428784891012586974258380350906625255961242443130286157885664260857440235952354925000777353590796274952836151639520964606157865934675160485092641000000000000000000000000]
Julia
<lang julia>using Primes
function proddivisors(n)
f = [one(n)] for (p, e) in factor(n) f = reduce(vcat, [f * p^j for j in 1:e], init = f) end return prod(f)
end
for i in 1:50
print(lpad(proddivisors(i), 10), i % 10 == 0 ? " \n" : "")
end
</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Kotlin
<lang scala>import kotlin.math.pow
private fun divisorCount(n: Long): Long {
var nn = n var total: Long = 1 // Deal with powers of 2 first while (nn and 1 == 0L) { ++total nn = nn shr 1 } // Odd prime factors up to the square root var p: Long = 3 while (p * p <= nn) { var count = 1L while (nn % p == 0L) { ++count nn /= p } total *= count p += 2 } // If n > 1 then it's prime if (nn > 1) { total *= 2 } return total
}
private fun divisorProduct(n: Long): Long {
return n.toDouble().pow(divisorCount(n) / 2.0).toLong()
}
fun main() {
val limit: Long = 50 println("Product of divisors for the first $limit positive integers:") for (n in 1..limit) { print("%11d".format(divisorProduct(n))) if (n % 5 == 0L) { println() } }
}</lang>
- Output:
Product of divisors for the first 50 positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
MAD
<lang MAD> NORMAL MODE IS INTEGER
DIMENSION D(50) THROUGH INIT, FOR I=1, 1, I.G.50
INIT D(I)=1
THROUGH CALC, FOR I=1, 1, I.G.50 THROUGH CALC, FOR J=I, I, J.G.50
CALC D(J) = D(J)*I
THROUGH SHOW, FOR I=1, 5, I.G.50
SHOW PRINT FORMAT F5, D(I), D(I+1), D(I+2), D(I+3), D(I+4)
VECTOR VALUES F5 = $5(I10)*$ END OF PROGRAM </lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Nim
<lang Nim>import math, strutils
func divisors(n: Positive): seq[int] =
result = @[1, n] for i in 2..sqrt(n.toFloat).int: if n mod i == 0: let j = n div i result.add i if i != j: result.add j
echo "Product of divisors for the first 50 positive numbers:" for n in 1..50:
stdout.write ($prod(n.divisors)).align(10), if n mod 5 == 0: '\n' else: ' '</lang>
- Output:
Product of divisors for the first 50 positive numbers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Perl
<lang perl>#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Product_of_divisors use warnings;
my @products = ( 1 ) x 51; for my $n ( 1 .. 50 )
{ $n % $_ or $products[$n] *= $_ for 1 .. $n; }
printf . (('%11d' x 5) . "\n") x 10, @products[1 .. 50];</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Phix
imperative
for i=1 to 50 do printf(1,"%,12d",{product(factors(i,1))}) if remainder(i,5)=0 then puts(1,"\n") end if end for
- Output:
1 2 3 8 5 36 7 64 27 100 11 1,728 13 196 225 1,024 17 5,832 19 8,000 441 484 23 331,776 125 676 729 21,952 29 810,000 31 32,768 1,089 1,156 1,225 10,077,696 37 1,444 1,521 2,560,000 41 3,111,696 43 85,184 91,125 2,116 47 254,803,968 343 125,000
functional
same output
sequence r = apply(apply(true,factors,{tagset(50),{1}}),product) puts(1,join_by(apply(true,sprintf,{{"%,12d"},r}),1,5,""))
Python
Finding divisors efficiently
<lang Python>def product_of_divisors(n):
assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans
if __name__ == "__main__":
print([product_of_divisors(n) for n in range(1,51)])</lang>
- Output:
[1, 2, 3, 8, 5, 36, 7, 64, 27, 100, 11, 1728, 13, 196, 225, 1024, 17, 5832, 19, 8000, 441, 484, 23, 331776, 125, 676, 729, 21952, 29, 810000, 31, 32768, 1089, 1156, 1225, 10077696, 37, 1444, 1521, 2560000, 41, 3111696, 43, 85184, 91125, 2116, 47, 254803968, 343, 125000]
Choosing the right abstraction
This is really an exercise in defining a divisors function, and the only difference between the suggested Sum and Product draft tasks boils down to two trivial morphemes:
reduce(add, divisors(n), 0) vs reduce(mul, divisors(n), 1)
The goal of Rosetta code (see the landing page) is to provide contrastive insight (rather than comprehensive coverage of homework questions :-). Perhaps the scope for contrastive insight in the matter of divisors is already exhausted by the trivially different Proper divisors task.
<lang python>Sums and products of divisors
from math import floor, sqrt from functools import reduce from operator import add, mul
- divisors :: Int -> [Int]
def divisors(n):
List of all divisors of n including n itself. root = floor(sqrt(n)) lows = [x for x in range(1, 1 + root) if 0 == n % x] return lows + [n // x for x in reversed(lows)][ (1 if n == (root * root) else 0): ]
- ------------------------- TEST -------------------------
- main :: IO ()
def main():
Product and sums of divisors for each integer in range [1..50] print('Products of divisors:') for n in range(1, 1 + 50): print(n, '->', reduce(mul, divisors(n), 1))
print('Sums of divisors:') for n in range(1, 1 + 100): print(n, '->', reduce(add, divisors(n), 0))
- MAIN ---
if __name__ == '__main__':
main()</lang>
Quackery
factors
is defined at Factors of an integer#Quackery.
<lang Quackery> [ 1 swap factors witheach * ] is product-of-divisors ( n --> n )
[] [] 50 times [ i^ 1+ product-of-divisors join ] witheach [ number$ nested join ] 75 wrap$
</lang>
- Output:
1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Raku
Yet more tasks that are tiny variations of each other. Tau function, Tau number, Sum of divisors and Product of divisors all use code with minimal changes. What the heck, post 'em all.
<lang perl6>use Prime::Factor:ver<0.3.0+>; use Lingua::EN::Numbers;
say "\nTau function - first 100:\n", # ID (1..*).map({ +.&divisors })[^100]\ # the task .batch(20)».fmt("%3d").join("\n"); # display formatting
say "\nTau numbers - first 100:\n", # ID (1..*).grep({ $_ %% +.&divisors })[^100]\ # the task .batch(10)».&comma».fmt("%5s").join("\n"); # display formatting
say "\nDivisor sums - first 100:\n", # ID (1..*).map({ [+] .&divisors })[^100]\ # the task .batch(20)».fmt("%4d").join("\n"); # display formatting
say "\nDivisor products - first 100:\n", # ID (1..*).map({ [×] .&divisors })[^100]\ # the task .batch(5)».&comma».fmt("%16s").join("\n"); # display formatting</lang>
- Output:
Tau function - first 100: 1 2 2 3 2 4 2 4 3 4 2 6 2 4 4 5 2 6 2 6 4 4 2 8 3 4 4 6 2 8 2 6 4 4 4 9 2 4 4 8 2 8 2 6 6 4 2 10 3 6 4 6 2 8 4 8 4 4 2 12 2 4 6 7 4 8 2 6 4 8 2 12 2 4 6 6 4 8 2 10 5 4 2 12 4 4 4 8 2 12 4 6 4 4 4 12 2 6 6 9 Tau numbers - first 100: 1 2 8 9 12 18 24 36 40 56 60 72 80 84 88 96 104 108 128 132 136 152 156 180 184 204 225 228 232 240 248 252 276 288 296 328 344 348 360 372 376 384 396 424 441 444 448 450 468 472 480 488 492 504 516 536 560 564 568 584 600 612 625 632 636 640 664 672 684 708 712 720 732 776 792 804 808 824 828 852 856 864 872 876 880 882 896 904 936 948 972 996 1,016 1,040 1,044 1,048 1,056 1,068 1,089 1,096 Divisor sums - first 100: 1 3 4 7 6 12 8 15 13 18 12 28 14 24 24 31 18 39 20 42 32 36 24 60 31 42 40 56 30 72 32 63 48 54 48 91 38 60 56 90 42 96 44 84 78 72 48 124 57 93 72 98 54 120 72 120 80 90 60 168 62 96 104 127 84 144 68 126 96 144 72 195 74 114 124 140 96 168 80 186 121 126 84 224 108 132 120 180 90 234 112 168 128 144 120 252 98 171 156 217 Divisor products - first 100: 1 2 3 8 5 36 7 64 27 100 11 1,728 13 196 225 1,024 17 5,832 19 8,000 441 484 23 331,776 125 676 729 21,952 29 810,000 31 32,768 1,089 1,156 1,225 10,077,696 37 1,444 1,521 2,560,000 41 3,111,696 43 85,184 91,125 2,116 47 254,803,968 343 125,000 2,601 140,608 53 8,503,056 3,025 9,834,496 3,249 3,364 59 46,656,000,000 61 3,844 250,047 2,097,152 4,225 18,974,736 67 314,432 4,761 24,010,000 71 139,314,069,504 73 5,476 421,875 438,976 5,929 37,015,056 79 3,276,800,000 59,049 6,724 83 351,298,031,616 7,225 7,396 7,569 59,969,536 89 531,441,000,000 8,281 778,688 8,649 8,836 9,025 782,757,789,696 97 941,192 970,299 1,000,000,000
REXX
<lang rexx>/*REXX program displays the first N product of divisors (shown in a columnar format).*/ numeric digits 20 /*ensure enough decimal digit precision*/ parse arg n cols . /*obtain optional argument from the CL.*/ if n== | n=="," then n= 50 /*Not specified? Then use the default.*/ if cols== | cols=="," then cols= 5 /* " " " " " " */ say ' index │'center("product of divisors", 102) /*display title for the column #s*/ say '───────┼'center("" , 102,'─') /* " " separator (above)*/ w= max(20, length(n) ) /*W: used to align 1st output column. */ $=; idx= 1 /*$: the output list, shown in columns*/
do j=1 for N /*process N positive integers. */ $= $ || right( commas( sigma(j) ), 20) /*add a sigma (sum) to the output list.*/ if j//cols\==0 then iterate /*Not a multiple of cols? Don't display*/ say center(idx, 7)'│' $ /*display partial list to the terminal.*/ idx= idx + cols /*bump the index number for the output.*/ $= /*start with a blank line for next time*/ end /*j*/
if $\== then say center(idx, 7)' ' $ /*any residuals sums left to display? */ say '───────┴'center("" , 102,'─') /* " " separator (above)*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? /*──────────────────────────────────────────────────────────────────────────────────────*/ sigma: procedure; parse arg x; if x==1 then return 1; odd=x // 2 /* // ◄──remainder.*/
p= x /* [↓] only use EVEN or ODD integers.*/ do k=2+odd by 1+odd while k*k<x /*divide by all integers up to √x. */ if x//k==0 then p= p * k * (x % k) /*multiple the two divisors to product.*/ end /*k*/ /* [↑] % is the REXX integer division*/ if k*k==x then return p * k /*Was X a square? If so, add √ x */ return p /*return (sigma) sum of the divisors. */</lang>
- output when using the default input:
index │ product of divisors ───────┼────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ 1 2 3 8 5 6 │ 36 7 64 27 100 11 │ 11 1,728 13 196 225 16 │ 1,024 17 5,832 19 8,000 21 │ 441 484 23 331,776 125 26 │ 676 729 21,952 29 810,000 31 │ 31 32,768 1,089 1,156 1,225 36 │ 10,077,696 37 1,444 1,521 2,560,000 41 │ 41 3,111,696 43 85,184 91,125 46 │ 2,116 47 254,803,968 343 125,000 ───────┴──────────────────────────────────────────────────────────────────────────────────────────────────────
Ring
<lang ring> limit = 50 row = 0
see "working..." + nl
for n = 1 to limit
pro = 1 for m = 1 to n if n%m = 0 pro = pro*m ok next see "" + pro + " " row = row + 1 if row % 5 = 0 see nl ok
next
see "done..." + nl </lang>
- Output:
working... 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000 done...
Ruby
<lang ruby>def divisor_count(n)
total = 1 # Deal with powers of 2 first while n % 2 == 0 do total = total + 1 n = n >> 1 end # Odd prime factors up to the square root p = 3 while p * p <= n do count = 1 while n % p == 0 do count = count + 1 n = n / p end total = total * count p = p + 2 end # If n > 1 then it's prime if n > 1 then total = total * 2 end return total
end
def divisor_product(n)
return (n ** (divisor_count(n) / 2.0)).floor
end
LIMIT = 50 print "Product of divisors for the first ", LIMIT, " positive integers:\n" for n in 1 .. LIMIT
print "%11d" % [divisor_product(n)] if n % 5 == 0 then print "\n" end
end</lang>
- Output:
Product of divisors for the first 50 positive integers: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000
Wren
<lang ecmascript>import "/math" for Int, Nums import "/fmt" for Fmt
System.print("The products of positive divisors for the first 50 positive integers are:") for (i in 1..50) {
Fmt.write("$9d ", Nums.prod(Int.divisors(i))) if (i % 5 == 0) System.print()
}</lang>
- Output:
The products of positive divisors for the first 50 positive integers are: 1 2 3 8 5 36 7 64 27 100 11 1728 13 196 225 1024 17 5832 19 8000 441 484 23 331776 125 676 729 21952 29 810000 31 32768 1089 1156 1225 10077696 37 1444 1521 2560000 41 3111696 43 85184 91125 2116 47 254803968 343 125000