25
\$\begingroup\$

Write a program that displays on the screen the sum of the divisors of a number (1 ≤ N ≤ 100) entered by the user in the range of 1 to N.

This is OEIS A000203.


Examples:

Input: 7

7 / 1 = 7
7 / 7 = 1

7 + 1 = 8

Output: 8


Input: 15

15 / 1 = 15
15 / 3 = 5
15 / 5 = 3
15 / 15 = 1

15 + 5 + 3 + 1 = 24

Output: 24


Input: 20

20 / 1 = 20
20 / 2 = 10
20 / 4 = 5
20 / 5 = 4
20 / 10 = 2
20 / 20 = 1

20 + 10 + 5 + 4 + 2 + 1 = 42

Output: 42


Input: 1

1 / 1 = 1

Output: 1


Input: 5

5 / 1 = 5
5 / 5 = 1

5 + 1 = 6

Output: 6

\$\endgroup\$
7
  • 6
    \$\begingroup\$ @H.PWiz I think he means "the divisors of a number N" \$\endgroup\$
    – benzene
    Sep 8, 2017 at 0:18
  • \$\begingroup\$ I think you mean sum of divisors, aka, the sigma function? \$\endgroup\$
    – Stephen
    Sep 8, 2017 at 0:18
  • \$\begingroup\$ Sorry, i mean "The sum of the multiple of N". \$\endgroup\$ Sep 8, 2017 at 0:19
  • \$\begingroup\$ @H.PWiz this is the sum of those, so I dunno \$\endgroup\$
    – Stephen
    Sep 8, 2017 at 0:21
  • \$\begingroup\$ @Stephen That seems like a trivial change to me \$\endgroup\$
    – H.PWiz
    Sep 8, 2017 at 0:21

57 Answers 57

1
2
1
\$\begingroup\$

Gaia, 2 bytes

Try it online!

Pretty straight-forward:

dΣ   - Full program.

d    - Divisors.
 Σ   - Sum.
\$\endgroup\$
1
\$\begingroup\$

Neim, 2 bytes

𝐅𝐬

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Octave, 20 bytes

@(n)~mod(n,t=1:n)*t'

Try it online!

\$\endgroup\$
1
\$\begingroup\$

PowerShell, 36 bytes

param($a)1..$a|%{$j+=$_*!($a%$_)};$j

Try it online!

Explanation

param($a)1..$a|%{$j+=$_*!($a%$_)};$j
param($a)                            # Takes input $a
         1..$a|%{               };   # For-loop from 1 up to $a
                          $a%$_      # Modulo, if this is zero we've hit a divisor
                        !(     )     # Take the Boolean-not of that. If a divisor, it's 1
                     $_*             # Multiply the current number by that Boolean
                                     # Only if it's a divisor will this be non-zero
                 $j+=                # Add it into our accumulator
                                  $j # Output our accumulator
\$\endgroup\$
1
\$\begingroup\$

Axiom, 42 bytes

f(x:PI):PI==(x=1=>1;reduce(+,divisors(x)))

results

(19) -> [[i,f(i)] for i in [7,15,20,42,1,5] ]
   (19)  [[7,8],[15,24],[20,42],[42,96],[1,1],[5,6]]
                                          Type: List List PositiveInteger
\$\endgroup\$
1
  • \$\begingroup\$ Why is not possible upvote the answer of who write it? I have the suspect here people upvote their answer logging with some other login... I say that because in some question there are more star than the people answer... (so why give one star if you not participate to competition?) \$\endgroup\$
    – user58988
    Sep 9, 2017 at 9:52
1
\$\begingroup\$

Rockstar, 96 bytes

listen to N
X's0
T's0
while N-X
let X be+1
let D be N/X
turn up D
let T be+D is N/X and X

say T

Try it here (Code will need to be pasted in)

\$\endgroup\$
1
\$\begingroup\$

GolfScript, 15 bytes

~.,{.3$\%!*+}*+

Try it online!

~                # Parses the input to integer
 .,              # Makes an array with numbers from 0 to (N-1)
   {.3$\%!*+}    # This block goes to the top of the stack without being executed
             *   # Folds
              +  # Adds the input and the result

What the block does:

    .            # Duplicates the number of the array
     3$          # Makes a copy of N
       \%!       # Tests if the number of the array is a divisor of N
          *      # Multiplies, resulting in the divisor if it was divisible or 0 if it wasn't
           +     # Adds to the acumulator
\$\endgroup\$
1
\$\begingroup\$

x86-16 machine code, 18 bytes

00000000: 89c1 9988 0e09 0150 d40a 7502 02d4 58e2  .......P..u...X.
00000010: f2c3                                     ..

Listing:

89 C1           MOV  CX, AX                 ; input number as loop counter 
99              CWD                         ; zero DX as running sum 
            DIVLOOP:
88 0E 0109      MOV  BYTE PTR[AAM1+1], CL   ; move loop counter to divisor 
50              PUSH AX                     ; save input number 
            AAM1:
D4 0A           AAM                         ; ZF if (AL % CL == 0), AH = quotient
75 02           JNZ  END_LOOP               ; if not ZF, continue loop 
02 D4           ADD  DL, AH                 ; otherwise add to running sum 
            END_LOOP:
58              POP  AX                     ; restore input number 
E2 F2           LOOP DIVLOOP                ; loop until CL == 0 
C3              RET                         ; return to caller

Callable function, input N in AX, result in DX.

Inspired by @CodyGray's excellent answer, and the comment "It sure seems like there should be a way to make this shorter" I just had to try!

As Cody mentioned, Using DIV/IDIV is inconvenient because it clobbers two registers including the dividend. Another is that the ZF flag is set when the quotient is 0, however in this case we're only interested in when the remainder is 0. Enter AAM, a trusty and underrated byte-sized division/modulo instruction that can be golfy. Even though it does clobber the dividend just like DIV, it will set ZF when the remainder is 0 which is what we want here. It's downside is that the divisor is encoded in the instruction opcode, which can be modified at runtime at a cost of 4 bytes (in real mode at least).

\$\endgroup\$
2
  • \$\begingroup\$ this is for MS-DOS ? what assembler and debugger you using ? TASM ? \$\endgroup\$ Sep 19, 2020 at 16:22
  • \$\begingroup\$ @NotStar I use MASM 1.1 for DOS asm and then just DOS DEBUG.EXE for the x86-16 stuff. Quick and dirty! \$\endgroup\$
    – 640KB
    Sep 19, 2020 at 21:06
1
\$\begingroup\$

Python 3, 45 bytes

lambda n:sum(i for i in range(1,n+1)if n%i<1)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Kotlin, 42 bytes

{var s=0;for(i in 1..it)if(it%i==0)s+=i;s}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

K (ngn/k), 14 bytes

{+/&~1!x%!1+x}

Try it online!

  • !1+x generate sequence from 1..x
  • x% divide the input by each term in this range
  • &~1! identify values in the range that evenly divide the input
  • +/ take (and implicitly return) their sum
\$\endgroup\$
1
\$\begingroup\$

Risky, 3 bytes

+/?+??

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Factor + math.primes.factors math.unicode, 15 bytes

[ divisors Σ ]

Try it online!

\$\endgroup\$
0
\$\begingroup\$

RProgN 2, 2 bytes

ƒ+

Explained

ƒ+
ƒ   # Factorize
 +  # Sum

Trivial, but felt it needed to be posted.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Perl 5, 35 + 1 (-p) = 36 bytes

$\+=($n%$_==0)&&$_ for 1..($n=$_)}{

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Bash + GNU utilities, 36

bc<<<`seq -f"n=%g;a+=n*!$1%%n;" $1`a

Try it online.


Pure Bash, 41

for((;++i<=$1;a+=$1%i?0:i))
{
:
}
echo $a

Try it online.

I first tried a fancy bash expansion answer, but it ended up being longer than the simple loop above:

echo $[$(eval echo +\\\(n={1..$1},$1%n?0:n\\\))]
\$\endgroup\$
0
\$\begingroup\$

QBIC, 17 bytes

[:|~b%a|\p=p+a}?p

Explanation

[:|      FOR a = 1; a <= b (read from cmd line); a++
~b%a|    IF b modulo a has a remainder THEN - empty block - 
\p=p+a   ELSE add divisor 'a' to running total 'p'
}        END IF, NEXT
?p       PRINT p
\$\endgroup\$
0
\$\begingroup\$

CJam, 16 bytes

ri:X{)_X\%!*}%:+

Try it online!

Explanation

ri                 e# Read integer, n
  :X               e# Write to variable X
    {       }%     e# Map this block over the array [0 1 ... n-1]
     )             e# Increment current value. Will give 1, 2, ..., n
      _            e# Duplicate
       X           e# Push input
        \          e# Swap
         %         e# Modulus
          !        e# Negate
           *       e# Multiply
              :+   e# Sum of array. Implicitly display
\$\endgroup\$
0
\$\begingroup\$

Jelly, 2 bytes

Æs

Try it online!

Built-in that does exactly as wanted.

\$\endgroup\$
4
  • \$\begingroup\$ Jelly seems so beautiful! Where can i find some stuff to study about it? \$\endgroup\$ Sep 8, 2017 at 0:41
  • \$\begingroup\$ @KevinHalley You can check out the Tutorial page on Github, or you can visit the official Jelly chatroom once you have 20 reputation, or the Jelly training chatroom, also at 20 reputation, which you'll need to request permission to train in \$\endgroup\$
    – hyper-neutrino
    Sep 8, 2017 at 0:42
  • 4
    \$\begingroup\$ I desperately want to upvote this because you suggested not upvoting trivial solutions. \$\endgroup\$
    – Cody Gray
    Sep 8, 2017 at 6:01
  • \$\begingroup\$ @CodyGray Yeah, maybe there's no point putting that there :P \$\endgroup\$
    – hyper-neutrino
    Sep 8, 2017 at 12:00
0
\$\begingroup\$

C#, 56 bytes


Data

  • Input Int32 i A number
  • Output Int32 The sum of the divisors of the number

Golfed

i=>{int s=0,d=1;for(;d<=i;d++)s+=i%d<1?i/d:0;return s;};

Ungolfed

i => {
    int
        s = 0,
        d = 1;
        
    for( ; d <= i; d++ )
        s += i % d < 1 ? i / d : 0;
    
    return s;
};

Ungolfed readable

// Takes an int
i => {
    // Initializes the sum 's' and divider 'd' vars
    int
        s = 0,
        d = 1;
        
    // Cycles each number lower than the the number 'i'
    for( ; d <= i; d++ )
    
        // Sums the result of the division between 'i' and 'd' if the modulus is 0
        s += i % d < 1 ? i / d : 0;
    
    // Returns the sum
    return s;
};

Full code

using System;
using System.Collections.Generic;

namespace TestBench {
    public class Program {
        // Methods
        static void Main( string[] args ) {
            Func<Int32, Int32> f = i => {
                int s = 0, d = 1;

                for( ; d <= i; d++ )
                    s += i % d < 1 ? i / d : 0;

                return s;
            };

            List<Int32>
                testCases = new List<Int32>() {
                    7,
                    15,
                    20,
                    42,
                    1,
                    5,
                };

            foreach( Int32 testCase in testCases ) {
                Console.WriteLine( $" INPUT: {testCase}\nOUTPUT: {f( testCase )}" );
            }

            Console.ReadLine();
        }
    }
}

Releases

  • v1.0 - 56 bytes - Initial solution.

Notes

  • None
\$\endgroup\$
1
  • \$\begingroup\$ In this statement s+=i%d<1?i/d:0;, you can save 2 bytes by replacing i/d by d, the results will be the same ( mostly because it will add the same numbers by in the reverse order : For example, in the second test case, all the division result are added : 15+5+3+1=24. If you add all the denominators ( i believe it's the word to describe the number used to divide the input, sorry if it's the wrong word, i'm not a native english speaker ), we get : 1+3+5+15=24, which is the same ) \$\endgroup\$ Sep 8, 2017 at 20:03
0
\$\begingroup\$

Batch, 70 bytes

@set/ai=%2+1,s=%3+i*!(%1%%i)
@if not %i%==%1 %0 %1 %i% %s%
@echo %s%

Alternative solution, also 70 bytes:

@set s=0
@for /l %%i in (1,1,%1)do @set/as+=%%i*!(%1%%%%i)
@echo %s%
\$\endgroup\$
0
\$\begingroup\$

MY, 4 bytes

ωḊΣ↵

Try it online!

How?

It's really simple: ω is the argument, is divisors, Σ is sum, is output. I thought I already answered this challenge, for some reason.

\$\endgroup\$
0
\$\begingroup\$

APL, 9 bytes

+/⍳×0=⍳|⊢

Try it online!

How? (input n)

  • ⍳|⊢, [n mod 1, ..., n mod n]
  • 0=, [0 == n mod 1, ... 0 == n mod n]
  • ⍳×, [1*(0 == n mod 1), ..., n*(0 == n mod n)]
  • +/, sum([1*(0 == n mod 1), ..., n*(0 == n mod n)])
\$\endgroup\$
0
\$\begingroup\$

Ruby, 29 bytes

->x{(1..x).sum{|r|x%r>0?0:r}}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Recursiva, 20 18 bytes

smBa++'%'Va'a:0!a'

Try it online!

Explanation:

smBa++'%'Va'a:0!a' - Input to a; 20
s                    - sum up; 42
 m                   - map with; [1, 0, 3, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15]
  Ba                 - Range; [1,2..20]
    ++'%'Va'a:0!a'   - function, evaluates to 0 if param cannot divide a i.e. 20
\$\endgroup\$
0
\$\begingroup\$

Clojure, 53 bytes

#(apply +(for[i(range 1(inc %)):when(=(mod % i)0)]i))
\$\endgroup\$
0
\$\begingroup\$

Casio-Basic, 42 bytes

sum(seq(piecewise(n/x=int(n/x),x,0),x,1,n

The piecewise acts as a shorter If statement. seq loops values of x from 1 to n, and the piecewise returns x if the number is a factor, otherwise it returns 0. sum adds the whole list together to output the total.

41 bytes for the function, +1 to add n in the parameters box.

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.