Sum of divisors: Difference between revisions
Content added Content deleted
(Added Algol 68) |
(→{{header|Nim}}: Added Lua) |
||
Line 1,483: | Line 1,483: | ||
{{out}} |
{{out}} |
||
<pre>{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}</pre> |
<pre>{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}</pre> |
||
=={{header|Lua}}== |
|||
{{Trans|C++}}...via Algol 68 |
|||
<syntaxhighlight lang="lua"> |
|||
do -- sum the divisors of the first 100 positive integers |
|||
-- computes the sum of the divisors of v using the prime factorisation |
|||
function divisor_sum( v ) |
|||
local total, power, n = 1, 2, v |
|||
while n % 2 == 0 do -- Deal with powers of 2 first |
|||
total = total + power |
|||
power = power * 2 |
|||
n = math.floor( n / 2 ) |
|||
end |
|||
local p = 3 -- Odd prime factors up to the square root |
|||
while ( p * p ) <= n do |
|||
local sum = 1 |
|||
power = p |
|||
while n % p == 0 do |
|||
sum = sum + power |
|||
power = power * p |
|||
n = math.floor( n / p ) |
|||
end |
|||
p = p + 2 |
|||
total = total * sum |
|||
end |
|||
if n > 1 then total = total * ( n + 1 ) end -- If n > 1 then it's prime |
|||
return total |
|||
end |
|||
-- show the first 100 divisor sums |
|||
local limit = 100 |
|||
io.write( "Sum of divisors for the first ", limit, " positive integers:\n" ) |
|||
for n = 1, limit do |
|||
io.write( string.format( " %4d", divisor_sum( n ) ) ) |
|||
if n % 10 == 0 then io.write( "\n" ) end |
|||
end |
|||
end |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sum of divisors for the first 100 positive integers: |
|||
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 |
|||
</pre> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |