Find the sum of the divisors of N

20

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

Kevin Halley

Posted 2017-09-08T00:14:43.663

Reputation: 235

6@H.PWiz I think he means "the divisors of a number N" – benzene – 2017-09-08T00:18:47.383

I think you mean sum of divisors, aka, the sigma function?

– Stephen – 2017-09-08T00:18:48.257

Sorry, i mean "The sum of the multiple of N". – Kevin Halley – 2017-09-08T00:19:35.420

@H.PWiz this is the sum of those, so I dunno – Stephen – 2017-09-08T00:21:11.987

@Stephen That seems like a trivial change to me – H.PWiz – 2017-09-08T00:21:53.623

Oh, and that question is restricted by time complexity, so maybe not. – H.PWiz – 2017-09-08T00:23:15.347

Closely related – Peter Taylor – 2017-09-08T06:25:45.853

Answers

19

05AB1E, 2 bytes

ÑO

Try it online!

How?

Ñ    Divisors
 O   Sum

H.PWiz

Posted 2017-09-08T00:14:43.663

Reputation: 10 962

Polyglot with 2sable – Mr. Xcoder – 2017-09-08T09:31:12.290

11ÑO - Rejecting the challenge and winning at the same time. That's pretty badass. – Lord Farquaad – 2017-09-08T20:26:52.233

6

x86-64 Machine Code, 23 bytes

89 F9 89 FE EB 0D 89 F8 99 F7 F1 85 D2 99 0F 44 D1 01 D6 E2 F1 96 C3

The above bytes of code define a function that accepts a single integer, N, and returns the sum of its multiples as a result.

The single parameter is passed in the EDI register, consistent with the System V AMD64 ABI (as used on *nix-style systems). The result is returned in the EAX register, as with all x86 calling conventions.

The algorithm is a very straightforward one, similar to many of the other submissions in other languages. We loop N times, each time computing the modulo and adding that to our running total.

Ungolfed assembly mnemonics:

; unsigned SumOfMultiples(unsigned N  /* (EDI) */)
    mov     ecx, edi      ; make copy of input N, to be used as our loop counter
    mov     esi, edi      ; make copy of input N, to be used as our accumulator
    jmp     CheckEnd      ; jump directly to 'CheckEnd'
AddModulo:
    mov     eax, edi      ; make copy of input N, to be used as input to DIV instruction
    cdq                   ; short way of setting EDX to 0, based on EAX
    div     ecx           ; divide EDX:EAX by ECX, placing remainder in EDX
    test    edx, edx      ; test remainder, and set ZF if it is zero
    cdq                   ; again, set EDX to 0, without clobbering flags
    cmovz   edx, ecx      ; set EDX to ECX only if remainder was zero (EDX = ZF ? 0 : ECX)
    add     esi, edx      ; add EDX to accumulator
CheckEnd:
    loop    AddModulo     ; decrement loop counter (ECX), and keep looping if it != 0
    xchg    eax, esi      ; move result from accumulator (ESI) into EAX
    ret                   ; return, with result in EAX

Try it online!

It sure seems like there should be a way to make this shorter, but I can't see it. Computing modulo on x86 takes quite a bit of code, since you do it using the DIV (or IDIV) instruction, and both of those use fixed input registers (EDX and EAX), the values of which get clobbered (because they receive the results, the remainder and quotient, respectively).

The only real tricks here are pretty standard golfing ones:

  • I've structured the code in a somewhat unusual way so that I can use the CISC-style LOOP instruction, which is basically just a combination of DEC+JNZ with the ECX register as the implicit operand.
  • I'm using XCHG at the end instead of MOV because the former has a special 1-byte encoding when EAX is one of the operands.
  • I use CDQ to zero out EDX in preparation for the division, even though for unsigned division you would ordinarily just zero it using a XOR. However, XOR is always 2 bytes, while CDQ is only 1 byte. I use CDQ again a second time inside of the loop to zero EDX, before the CMOVZ instruction. This works because I can be guaranteed that the quotient of the division (in EAX) is always unsigned, so a sign-extension into EDX will set EDX equal to 0.

Cody Gray

Posted 2017-09-08T00:14:43.663

Reputation: 2 639

4

C (gcc), 45 bytes

i,s;f(n){for(s=i=n;--i;)s+=n%i?0:i;return s;}

Try it online!

tsh

Posted 2017-09-08T00:14:43.663

Reputation: 13 072

3

Mathematica, 14 bytes

Tr@Divisors@#&   

or an answer by @Loki

Mathematica, 17 bytes

DivisorSum[#,#&]&

J42161217

Posted 2017-09-08T00:14:43.663

Reputation: 15 931

@Jennymathy Very nice, thanks! An equivalent and funny way to write it is also: DivisorSum[#, # &] & – Rebel-Scum – 2017-09-08T18:15:34.603

@Jennymathy Hmm, this is even better: Total@Divisors@ is only 15 characters long! And it works: eg Total@Divisors@15 gives 24 as expected. Mathematica FTW :) – Rebel-Scum – 2017-09-08T19:27:48.227

2@Loki and Tr@Divisors@#& even better ;-) – J42161217 – 2017-09-08T19:29:48.457

@Jennymathy Wow, awesome! – Rebel-Scum – 2017-09-08T19:30:41.010

@Jennymathy, actually you don't even need the #&, Tr@Divisors@ also just works, ie Tr@Divisors@15 gives 24 – Rebel-Scum – 2017-09-08T19:32:03.913

1@Loki the program must be a function f= that takes an input f[x] that's why I present it in this way.Welcome to PPCG – J42161217 – 2017-09-08T19:36:32.050

3You can use Tr@*Divisors to shave off a byte. – wchargin – 2017-09-09T01:52:17.003

3

Japt, 3 bytes

â)x

Try it online!

powelles

Posted 2017-09-08T00:14:43.663

Reputation: 1 277

Alternative: â x – Mr. Xcoder – 2017-09-08T22:11:38.900

@Mr.Xcoder: not really an alternative; it's doing the exact same thing - only difference is the choice of parenthesising. – Shaggy – 2017-10-10T16:57:57.397

Or with the flag -x, it could be one byte – Embodiment of Ignorance – 2019-04-20T19:30:26.500

3

Shnap, 44 43 bytes

-1 bye thanks to Mr. Xcoder (lol I was outgolfed in my own language)

 $n return:{s=0for d:range(n+1)if n%d<1s+=d}

This is a function ($ starts a function in Shnap).

Try it online!

Explanation:

$ n                        //Start function with parameter n
    return: {              //Technically, we are returning a scope-block, which evaluates to the last statement run
        s = 0              //Our result
        for d : range(n+1) //For each value in the iterator range(n+1)
            if n % d < 1  // If n is divisible by d
                s += d     // Add d to the sum
                           // Since (s += d) returns (s + d), and a scope-block returns the last run statement, this will be the last statement and equal to our result
    }

Noncompeting, 19 bytes

After many language updates, this can now be reduced to a measly 19 bytes:

$n=>sum(factors(n))

Try it online!

Socratic Phoenix

Posted 2017-09-08T00:14:43.663

Reputation: 1 629

1==0 is <1 (43 bytes) – Mr. Xcoder – 2017-09-08T09:22:19.137

@Mr. Xcoder thanks... I was outgolfed... In my own language... Which isn't even esoteric xD – Socratic Phoenix – 2017-09-08T10:51:50.147

3

Brachylog, 2 bytes

f+

Try it online!

Explanation

f       Factors
 +      Sum

Fatalize

Posted 2017-09-08T00:14:43.663

Reputation: 32 976

3

C, C++, C#, D, Java, 65 62 bytes

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

This works in all theses 5 programming languages because of similarities.

C, C++ and D optimization : 62 60 bytes

In C++ and D, integers convert implicitly to booleans ( Zero => false, Not Zero => true ), so you don't need to have the !=0

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

D optimization : golfy template system, 55 bytes

T d(T)(T n){T s,i=1;for(;i<=n;++i)s+=n%i?0:i;return s;}

Code to test :

C :

printf("%d %d %d %d %d", d(7), d(15), d(20), d(1), d(5));

C++ :

std::cout << d(7) << ' ' << d(15) << ' ' << d(20) << ' ' << d(1) << ' ' << d(5);

C# :

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

    static void Main(string[] args)
    {
        var f = new FindSum();
        Console.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}", f.d(7), f.d(15), f.d(20), f.d(1), f.d(5)));
    }
}

D :

writeln(d(7));
writeln(d(15));
writeln(d(20));
writeln(d(1));
writeln(d(5));

Java :

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

    public static void main(String[] args) {
        FindSum f = new FindSum();
        System.out.println(String.format("%d, %d, %d, %d, %d", f.d(7), f.d(15), f.d(20), f.d(1), f.d(5)));
    }
}

HatsuPointerKun

Posted 2017-09-08T00:14:43.663

Reputation: 1 891

A few things: First, I don't think you need parentheses around the n%i/n%i!=0 in any of the languages. Second, your first solution should be able to have n%i>0 instead of n%i!=0. Third, D's solution can be T d(T)(T n){T s,i=1;for(;i<=n;++i)s+=n%i?0:i;return s;} by abusing the template system and default values. – Zacharý – 2017-09-09T13:51:59.300

2

R, 31 26 bytes

function(N)(x=1:N)%*%!N%%x

Try it online!

Returns a 1x1 matrix.

Computes !N%%x maps elements d of 1:N by: d->(1 if d divides N, 0 otherwise)

Then x%*%x!N%%x is the matrix product of 1:N which results in the sum of x where !N%%x is 1. Neat! Technically a port of Luis Mendo's Octave answer but I only saw that after I thought of this.

R+ numbers, 14 bytes

numbers::Sigma

Try it online!

Giuseppe

Posted 2017-09-08T00:14:43.663

Reputation: 21 077

For the first one you can save 2 bytes with N=scan(); – gstats – 2017-09-08T12:07:34.357

@gstats yes, but then I should get +4 bytes per meta discussion. If you have a strong opinion you can weigh in on Jarko's answer but as nobody has suggested an alternative, that stands in my mind.

– Giuseppe – 2017-09-08T12:18:17.070

Shouldn't the second be numbers::Sigma(N)? Like this it outputs the source code of function Sigma. – Rui Barradas – 2017-09-08T15:58:32.233

@RuiBarradas a function is a perfectly good submission. to test it, you obviously have to call it as I do in the first submission. – Giuseppe – 2017-09-08T15:59:57.130

2

Javascript, 54 44 bytes

n=>[...Array(x=n)].reduce(y=>y+!(n%x)*x--,0)

Saved 10 bytes thanks to Shaggy

Try it online!

const f = n=>[...Array(x=n)].reduce(y=>y+!(n%x)*x--,0)

console.log(f(7))
console.log(f(15))
console.log(f(20))
console.log(f(1))
console.log(f(5))

powelles

Posted 2017-09-08T00:14:43.663

Reputation: 1 277

2

Python, 44 bytes

lambda k:sum(i*(k%i<1)for i in range(1,1+k))
  • Thanks to Stephen, save 1 byte by removing whitespace.
  • Thanks to Jonathan Frech, save another 1 byte by changing if to multiply.

tsh

Posted 2017-09-08T00:14:43.663

Reputation: 13 072

2

J, 23 bytes

[:+/](([:=&0]|[)#])1+i.

Try it online!

For J fans, there is a clever 13 byte solution: >:@#.~/.~&.q: but since it wasn't my invention I'm not posting it as my official answer.

My own solution simply filters 1..n, finding divisors, then sums them. The crux of it is the dyadic fork

](([:=&0]|[)#])

Note that in this context ] is 1..n, and [ is n itself. Hence ]|[ are the remainders when dividing each element of 1..n into n, and =&0 tells you if they're equal to 0.

Jonah

Posted 2017-09-08T00:14:43.663

Reputation: 8 729

2This for 13 bytes should be equivalent: +1#.i.*0=i.|] – miles – 2017-09-08T06:22:19.737

@miles, that is really nice. This part is i.|] is a great improvement on my approach. I don't fully understand this part though: +1#.i. -- could you explain it? – Jonah – 2017-09-08T06:27:12.863

21#. is base 1 conversion, which is equivalent to +/"1. First i.|] to get the remainders, then 0= to find the ones equal to 0 (the divisors), then i.* to zero out the non-divisors in the range, then sum using 1#., then add + itself since i. is an exclusive range. – miles – 2017-09-08T06:31:06.167

2

Java (OpenJDK 8), 53 51 bytes

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

Try it online!

Nevay

Posted 2017-09-08T00:14:43.663

Reputation: 421

1@corsiKa Only class fields. In a local scope they're unitialized. – shooqie – 2017-09-09T09:03:58.620

2

MATL, 6 bytes

t:\~fs

Try it online!

-4 bytes thanks to @LuisMendo

10 bytes

My previous solution using a loop

:"G@\~@*vs

Try it online!

3 bytes

Using built-in

Z\s

Try it online!

Cinaski

Posted 2017-09-08T00:14:43.663

Reputation: 1 588

2

Haskell, 30 bytes

f n=sum[i|i<-[1..n],n`mod`i<1]

Try it online!

shooqie

Posted 2017-09-08T00:14:43.663

Reputation: 5 032

2

Brain-Flak, 96 bytes

((({})<>){<(([()]{})){<>(({})(<()>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({})){((<{}{}>))}}{}>{}})

Try it online!

Explanation:

Now outdated by improvements.

The heart of the algorithm is this:

({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({})) turns |N, M...| into |N mod M, M...|
{((<{}{}>))} if the top of stack is not zero, replace it and the second with zero

That is a modification on mod that will give us M if it is a factor of N and 0 otherwise. Full code is below.

((({})<>) place input, N on both stacks
{ Loop to find factors
 <
  (([()]{})) Decrement and Duplicate; get next factor to check
  { if not zero
   (<>({})<>) Copy N from other stack
   ({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({})){((<{}{}>))} Code explained above
  }
  {} drop the zero
 >
 {} add the factor
}) push the sum

MegaTom

Posted 2017-09-08T00:14:43.663

Reputation: 3 787

Do you have an explanation? – Post Rock Garf Hunter – 2017-09-19T02:33:45.577

@FunkyComputerMan I got one now! – MegaTom – 2017-09-21T19:56:41.047

1

JavaScript, 31 bytes

f=(n,i=n)=>i&&!(n%i)*i+f(n,i-1)

tsh

Posted 2017-09-08T00:14:43.663

Reputation: 13 072

1

VBA (Excel), 73 bytes

a=Cells(1,1)
x=1
While x<=a
If a Mod x = 0 Then b=b+x
x=x+1
Wend
MsgBox b

remoel

Posted 2017-09-08T00:14:43.663

Reputation: 511

This answer is invalid as it is a collection of snippets that cannot be run as a single unit as stands. To make this valid you will need to convert this to a subroutine or an anonymous VBE immediate window function. – Taylor Scott – 2017-09-17T19:44:26.237

I am not very familiar in what you had said. Can you help me a bit more? – remoel – 2017-09-18T04:43:56.183

To make this post valid you would have to convert it into one of the following formats, 1 - Subroutine, 2 - Function, 3 - Anonymous VBE immediate window function (a single line that can be executed in the Immediate window); For your implementation, the simplest implementation of this would be to convert to a subroutine by wrapping with Sub Y...End Sub to get the 85 Byte solution Sub y A=Cells(1,1) x=1 While x<=A If A Mod x=0 Then b=b+x x=x+1 Wend MsgBox b End Sub – Taylor Scott – 2017-09-20T00:32:35.963

That however can be optimized quite heavily down to the 72 byte solution Sub y While x<=[A1] x=x+1 If [A1]Mod x=0Then b=b+x Wend Debug.?b End Sub which assumes that it is run in a clean module (x = default int value, 0) and outputs to the VBE immediate window (? autoformats to Print ) – Taylor Scott – 2017-09-20T00:34:51.347

Beyond this, and recognizing that your solution does not take input via the subroutine call, this can then be converted to a VBE immediate window function for 50 Bytes While x<=[A1]:x=x+1:b=IIf([A1]Mod x,b,b+x):Wend:?b which assumes that x,b are the default value of 0 and outputs to the VBE immediate window (from the VBE immediate window ? is equivalent to Debug.Print) – Taylor Scott – 2017-09-20T00:38:55.463

Note that in the above, the If ... Then clause was converted to an IIf call - if this is not possible and the If statement lies in a loop, then your subroutine / function cannot be made into an anonymous VBE immediate window function, as anything that follows the Then regardless of next lines (:) shall be regarded as part of that If statement and thus, the compiler sees an un-terminated loop structure – Taylor Scott – 2017-09-20T00:41:55.903

That's about all of the basics - see here for more.

– Taylor Scott – 2017-09-20T00:43:53.060

Thank You Sir @TaylorScott . I guess I really don't know a lot about the definitions in VBA. Yes I read about your post and it actually helped me a lot and understand more. Thank you again Sir. – remoel – 2017-09-20T03:14:39.963

1

Pari/GP, 5 bytes

sigma

Try it online!

alephalpha

Posted 2017-09-08T00:14:43.663

Reputation: 23 988

1

Python 2, 41 bytes

f=lambda n,i=1:i<=n and(n%i<1)*i+f(n,i+1)

Try it online!

Chas Brown

Posted 2017-09-08T00:14:43.663

Reputation: 8 959

1

Pyth, 6 bytes

s*M{yP

Try it here!

Pyth doesn't have a built-in for divisors, so I think this is reasonable.

Explanation

s*M{yP    - Full program with implicit input.

     P    - The prime factors of the input.
    y     - The powerset of its prime factors.
   {      - Deduplicate.
 *M       - Map with multiplication.
s         - Sum.
          - Implicitly display the result.

Given 20, for instance, this is what our program does after each instruction:

  • P: [2, 2, 5].

  • y: [[], [2], [2], [5], [2, 2], [2, 5], [2, 5], [2, 2, 5]].

  • {: [[], [2], [5], [2, 2], [2, 5], [2, 2, 5]].

  • *M: [1, 2, 5, 4, 10, 20].

  • s: 42.

Mr. Xcoder

Posted 2017-09-08T00:14:43.663

Reputation: 39 774

1

Ohm v2, 2 bytes

Try it online!

This is pretty straight-forwad:

V   - Divisors.
 Σ  - Sum.

Mr. Xcoder

Posted 2017-09-08T00:14:43.663

Reputation: 39 774

Damnit, you beat me too it! – ThePlasmaRailgun – 2017-12-11T03:52:29.620

1

Husk, 5 bytes

ṁΠuṖp

Try it online!

How?

ṁΠuṖp  - Full program, implicit input.

     p  - Prime factors.
    Ṗ   - Powerset.
   u    - Remove duplicates.
ṁΠ     - Get the product of each list, sum and implicitly output.

Thanks to Zgarb for the suggestions in chat!

Mr. Xcoder

Posted 2017-09-08T00:14:43.663

Reputation: 39 774

1

Octave, 20 bytes

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

Try it online!

Luis Mendo

Posted 2017-09-08T00:14:43.663

Reputation: 87 464

0

Jelly, 2 bytes

Æs

Try it online!

Built-in that does exactly as wanted.

HyperNeutrino

Posted 2017-09-08T00:14:43.663

Reputation: 26 575

Jelly seems so beautiful! Where can i find some stuff to study about it? – Kevin Halley – 2017-09-08T00:41:39.173

@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

– HyperNeutrino – 2017-09-08T00:42:53.863

3I desperately want to upvote this because you suggested not upvoting trivial solutions. – Cody Gray – 2017-09-08T06:01:49.747

@CodyGray Yeah, maybe there's no point putting that there :P – HyperNeutrino – 2017-09-08T12:00:12.037

0

RProgN 2, 2 bytes

ƒ+

Explained

ƒ+
ƒ   # Factorize
 +  # Sum

Trivial, but felt it needed to be posted.

Try it online!

ATaco

Posted 2017-09-08T00:14:43.663

Reputation: 7 898

0

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

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

Try it online!

Xcali

Posted 2017-09-08T00:14:43.663

Reputation: 7 671

0

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\\\))]

Digital Trauma

Posted 2017-09-08T00:14:43.663

Reputation: 64 644

0

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

officialaimm

Posted 2017-09-08T00:14:43.663

Reputation: 2 739

0

Add++, 9 bytes

D,f,@,dFs

Try it online!

I clearly got here too late. This defines a function that gets the factors, then sums them.

caird coinheringaahing

Posted 2017-09-08T00:14:43.663

Reputation: 13 702

0

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

steenbergh

Posted 2017-09-08T00:14:43.663

Reputation: 7 772

0

Gaia, 2 bytes

Try it online!

Pretty straight-forward:

dΣ   - Full program.

d    - Divisors.
 Σ   - Sum.

Mr. Xcoder

Posted 2017-09-08T00:14:43.663

Reputation: 39 774

0

Okx

Posted 2017-09-08T00:14:43.663

Reputation: 15 025

0

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

Luis Mendo

Posted 2017-09-08T00:14:43.663

Reputation: 87 464

0

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

auhmaan

Posted 2017-09-08T00:14:43.663

Reputation: 906

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 ) – HatsuPointerKun – 2017-09-08T20:03:26.823

0

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

AdmBorkBork

Posted 2017-09-08T00:14:43.663

Reputation: 41 581

0

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%

Neil

Posted 2017-09-08T00:14:43.663

Reputation: 95 035

0

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

RosLuP

Posted 2017-09-08T00:14:43.663

Reputation: 3 036

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?) – RosLuP – 2017-09-09T09:52:05.037

0

int divSum(int n)
{
    // Final result of sum of divisors
    int res = 0;

    // find all divisors which divides n
    for (int i=2; i<=sqrt(num); i++)
    {
        // if i is divisor of n
        if (num%i==0)
        {
            // if both divisors are same then add
            // it only once else add both
            if (i==(n/i))
                res += i;
            else
                res += (i + n/i);
        }
    }

    // Add 1 to the res as 1 is also a divisor
    return (res + 1);
}

Anit

Posted 2017-09-08T00:14:43.663

Reputation: 1

1Hello and welcome to PPCG! This question is a code golf, meaning that answers aim to be as short as possible. This code looks more like production code, and can definitely be golfed a great deal, by changing variable names to 1 character and removing extra white space and comments. – caird coinheringaahing – 2017-09-09T07:46:36.237

The name of language, and the bytes has to be in the 1st line; example #Pascal, 23 bytes. Than you can write the function golfed, and function ungolfed with comments (in the few I understand ) – RosLuP – 2017-09-09T09:44:51.730

0

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.

Zacharý

Posted 2017-09-08T00:14:43.663

Reputation: 5 710

0

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)])

Zacharý

Posted 2017-09-08T00:14:43.663

Reputation: 5 710

0

Ruby, 29 bytes

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

Try it online!

G B

Posted 2017-09-08T00:14:43.663

Reputation: 11 099

0

Excel VBA, 44 Bytes

Anonymous VBE immediate window function that takes input from [A1] and outputs to the VBE immediate window

For i=1To[A1]:s=s+IIf([A1]mod i,0,i):Next:?s

Taylor Scott

Posted 2017-09-08T00:14:43.663

Reputation: 6 709

0

Clojure, 53 bytes

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

NikoNyrh

Posted 2017-09-08T00:14:43.663

Reputation: 2 361

0

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.

numbermaniac

Posted 2017-09-08T00:14:43.663

Reputation: 639