Modulus Summation

27

I call this sequence "the Jesus sequence", because it is the sum of mod.</pun>

For this sequence, you take all the positive integers m less than the input n, and take the sum of n modulo each m. In other words:

$$a_n = \sum_{m=1}^{n-1}{n\bmod m}$$

For example, take the term 14:

14 % 1 = 0
14 % 2 = 0
14 % 3 = 2
14 % 4 = 2
14 % 5 = 4
14 % 6 = 2
14 % 7 = 0
14 % 8 = 6
14 % 9 = 5
14 % 10 = 4
14 % 11 = 3
14 % 12 = 2
14 % 13 = 1
0+0+2+2+4+2+0+6+5+4+3+2+1=31

Your goal here is to write a function that implements this sequence. You should take the sequence term (this will be a positive integer from 1 to 231) as the only input, and output the value of that term. This is OEIS A004125.

As always, standard loopholes apply and the shortest answer in bytes wins!

Nissa

Posted 2017-12-14T01:23:59.903

Reputation: 3 334

Answers

7

05AB1E, 3 bytes

L%O

Try it online!

Mr. Xcoder

Posted 2017-12-14T01:23:59.903

Reputation: 39 774

8

Haskell, 22 bytes

f x=sum$mod x<$>[1..x]

Try it online!

Explanation

Yes.

ბიმო

Posted 2017-12-14T01:23:59.903

Reputation: 15 345

5Great explanation – Esolanging Fruit – 2017-12-15T03:32:13.917

7

Ruby, 28 27 23 bytes

-4 bytes thanks to @daniero.

->n{(1..n).sum{|i|n%i}}

Try it online!

Ruby, 28 bytes

f=->n{n>($.+=1)?n%$.+f[n]:0}

Try it online!

Jordan

Posted 2017-12-14T01:23:59.903

Reputation: 5 001

6

Funky, 25 bytes

n=>fors=~-i=1i<n)s+=n%i++

Just the Naïve answer, seems to work.

Try it online!

Desmos, 25 bytes.

f(x)=\sum_{n=1}^xmod(x,n)

Paste into Desmos, then run it by calling f.

When pasted into Desmos, the latex looks like this

The graph however looks like

Although it looks random and all over the place, that's the result of only supporting integers.

RProgN 2, 9 bytes

x=x³x\%S+

Explained

x=x³x\%S+
x=          # Store the input in "x"
  x         # Push the input to the stack.
   ³x\%     # Define a function which gets n%x
       S    # Create a stack from "x" with the previous function. Thus this gets the range from (1,x), and runs (i%x) on each element.
        +   # Get the sum of this stack.

Try it online!

ReRegex, 71 bytes

#import math
(_*)_a$/d<$1_>b$1a/(\d+)b/((?#input)%$1)+/\+a//u<#input
>a

Try it online!

ARBLE, 19 bytes

sum(range(1,a)|a%i)

Try it online!

MaybeLater, 56 bytes

whenf is*{n=0whenx is*{ifx>0{n=n+f%x x--}elseprintn}x=f}

Try it online!

ATaco

Posted 2017-12-14T01:23:59.903

Reputation: 7 898

Will the submissions to this challenge ever end? So far I've been getting a new one every 40 minutes :P – Nissa – 2017-12-15T03:26:12.787

@StephenLeppik Oh I've still got more coming, don't worry. – ATaco – 2017-12-15T03:33:52.607

@StephenLeppik I'd rather not, because they're of various quality across various languages. – ATaco – 2017-12-15T03:42:41.197

@StephenLeppik I've combined them for you, begrudgingly. – ATaco – 2017-12-15T03:52:40.287

Thanks! Now you get an upvote because all this is lots of effort. – Nissa – 2017-12-15T13:57:57.423

4Please don't do this. Separate languages -- even separate approaches -- should go in separate answers. – Dennis – 2017-12-18T04:48:21.353

@Dennis Although I agree with you, OP said to do it this way, so I've done it this way. – ATaco – 2017-12-18T04:49:04.813

5

Jelly, 3 bytes

%RS

Explanation

%RS
 R   Range(input)  [1...n]
%    Input (implicit) modulo [1...n]->[n%1,n%2...n%n]
  S  Sum of the above

Try it online!

dylnan

Posted 2017-12-14T01:23:59.903

Reputation: 4 993

5

MATL, 4 bytes

t:\s

Try it online!

Explanation:

t      % Duplicate input. Stack: {n, n}
 :     % Range 1...n. Stack: {n, [1...n]}
  \    % Modulo. Stack: {[0,0,2,2,4,...]}
   s   % Sum. Implicitly display result.

Sanchises

Posted 2017-12-14T01:23:59.903

Reputation: 8 530

4

Ohm v2, 4 bytes

D@%Σ

Try it online!

Cinaski

Posted 2017-12-14T01:23:59.903

Reputation: 1 588

4

R, 20 bytes

sum((n=scan())%%1:n)

Try it online!

plannapus

Posted 2017-12-14T01:23:59.903

Reputation: 8 610

4

Python 2, 44 bytes

lambda n:sum(map(lambda x:x%(n-x),range(n)))

Try it online!

EDIT: Changed range(0,n) to range(n)

Max00355

Posted 2017-12-14T01:23:59.903

Reputation: 151

2Hello, and welcome to the site! range implicitly takes a first argument of 0, so you could shorten this by two bytes by doing range(n) instead. – James – 2017-12-19T08:27:30.443

Oh wow! I didn't even think of that. Thanks – Max00355 – 2017-12-19T19:26:43.440

1

Welcome to PPCG! You can use a list comprehension instead of map for 38 bytes: Try it online!

– Mr. Xcoder – 2017-12-19T19:40:28.073

You are right, but that was used in Neil's answer, so I wasn't sure if copying it would have been the best thing. Unless I am missing something here of course. I wanted to post the alternative, even if it was a bit longer. – Max00355 – 2017-12-19T19:52:30.393

3

JavaScript (ES6), 26 bytes

f=(n,k=n)=>n&&k%n+f(n-1,k)

Demo

f=(n,k=n)=>n&&k%n+f(n-1,k)

for(n = 1; n < 30; n++) {
  console.log('a(' + n + ') = ' + f(n))
}

Arnauld

Posted 2017-12-14T01:23:59.903

Reputation: 111 334

3

Python 3, 37 bytes

lambda a:sum(a%k for k in range(1,a))

Try it online!

Neil

Posted 2017-12-14T01:23:59.903

Reputation: 2 417

4 answers in 10 minutes? Wow. – Nissa – 2017-12-14T01:31:52.500

1Must be some very gifted programmers. ;) – Neil – 2017-12-14T01:32:32.493

3

Japt, 6 5 bytes

Saved 1 byte thanks to @Shaggy

Æ%XÃx

Test it online!

How it works

         Implicit: U = input number
Æ        Create the range [0, U),
 %XÃ       mapping each item X to U%X. U%0 gives NaN.
    x    Sum, ignoring non-numbers.
         Implicit: output result of last expression

ETHproductions

Posted 2017-12-14T01:23:59.903

Reputation: 47 880

3

Charcoal, 9 bytes

IΣEN﹪Iθ⊕ι

Try it online!

Link is to the verbose version of the code:

Print(Cast(Sum(Map(InputNumber(),Modulo(Cast(q),++(i))))));

Charlie

Posted 2017-12-14T01:23:59.903

Reputation: 11 448

3

Standard ML (MLton), 53 51 bytes

fn& =>let fun f 1a=a|f%a=f(% -1)(a+ &mod%)in f&0end

Try it online!

Ungolfed:

fn n =>
   let fun f 1 a = a
         | f x a = f (x-1) (a + n mod x)
   in  
       f n 0
   end

Previous 53 byte version:

fn n=>foldl op+0(List.tabulate(n-1,fn i=>n mod(i+1)))

Try it online!

Explanation:

List.tabulate takes an integer x and a function f and generates the list [f 0, f 1, ..., f(x-1)]. Given some number n, we call List.tabulate with n-1 and the function fn i=>n mod(i+1) to avoid dividing by zero. The resulting list is summed with foldl op+0.

Laikoni

Posted 2017-12-14T01:23:59.903

Reputation: 23 676

3

Java (OpenJDK 8), 45 bytes

n->{int m=n,s=0;for(;m-->1;)s+=n%m;return s;}

Try it online!

Olivier Grégoire

Posted 2017-12-14T01:23:59.903

Reputation: 10 647

1+1 For using the goes to (-->) operator. – raznagul – 2017-12-15T12:07:49.127

3

Mathematica, 18 bytes

#~Mod~i~Sum~{i,#}&

Try it online!

totallyhuman

Posted 2017-12-14T01:23:59.903

Reputation: 15 378

2same bytes Tr[#~Mod~Range@#]& – J42161217 – 2017-12-14T11:53:03.680

3

APL (Dyalog), 5 bytes

+/⍳|⊢

Try it online!

How?

Monadic train -

+/ - sum

- n

| - vectorized modulo

- the range of n

Uriel

Posted 2017-12-14T01:23:59.903

Reputation: 11 708

2

05AB1E, 6 bytes

ÎGIN%+

Try it online!

My first 05AB1E program ;)

Btw I got two 39s, 1 for JS6 and 1 for python, but I was too late

Explanation:

ÎGIN%+
Î                      # Push 0, then input, stack = [(accumulator = 0), I]
 G                     # For N in range(1, I), stack = [(accumulator)]
  IN                   # Push input, then N, stack = [(accumulator), I, N]
    %                  # Calculate I % N, stack = [(accumulator), I % N]
     +                 # Add the result of modulus to accumulator

Shieru Asakoto

Posted 2017-12-14T01:23:59.903

Reputation: 4 445

2

Windows Batch (CMD), 63 bytes

@set s=0
@for /l %%i in (1,1,%1)do @set/as+=%1%%%%i
@echo %s%

Previous 64-byte version:

@set/ai=%2+1,s=%3+%1%%i
@if %i% neq %1 %0 %1 %i% %s%
@echo %s%

Neil

Posted 2017-12-14T01:23:59.903

Reputation: 95 035

2

Ruby, 23 bytes

->n{(1..n).sum{|i|n%i}}

Try it online!

G B

Posted 2017-12-14T01:23:59.903

Reputation: 11 099

2

Julia 0.4, 15 bytes

x->sum(x%[1:x])

Try it online!

Lescurel

Posted 2017-12-14T01:23:59.903

Reputation: 171

2

Add++, 14 bytes

L,RAdx$p@BcB%s

Try it online!

How it works

L,   - Create a lambda function.
     - Example argument:     [7]
  R  - Range;        STACK = [[1 2 3 4 5 6 7]]
  A  - Argument;     STACK = [[1 2 3 4 5 6 7] 7]
  d  - Duplicate;    STACK = [[1 2 3 4 5 6 7] 7 7]
  x  - Repeat;       STACK = [[1 2 3 4 5 6 7] 7 [7 7 7 7 7 7 7]]
  $p - Swap and pop; STACK = [[1 2 3 4 5 6 7] [7 7 7 7 7 7 7]]
  @  - Reverse;      STACK = [[7 7 7 7 7 7 7] [1 2 3 4 5 6 7]]
  Bc - Zip;          STACK = [[7 1] [7 2] [7 3] [7 4] [7 5] [7 6] [7 7]]
  B% - Modulo each;  STACK = [0, 1, 1, 3, 2, 1, 0]
  s  - Sum;          STACK = [8]

caird coinheringaahing

Posted 2017-12-14T01:23:59.903

Reputation: 13 702

2

T-SQL, 80 79 bytes

-1 byte thanks to @MickyT

WITH c AS(SELECT @ i UNION ALL SELECT i-1FROM c WHERE i>1)SELECT SUM(@%i)FROM c

Receives input from an integer parameter named @, something like this:

DECLARE @ int = 14;

Uses a Common Table Expression to generate numbers from 1 to n. Then uses that cte to sum up the moduluses.

Note: a cte needs a ; between the previous statement and the cte. Most code I've seen puts the ; right before the declaration, but in this case I can save a byte by having it in the input statement (since technically my code by itself is the only statement).

Try it (SEDE)


The less "SQL-y" way is only 76 bytes. This time the input variable is @i instead of @ (saves one byte). This one just does a while loop.

DECLARE @ int=2,@o int=0WHILE @<@i BEGIN SELECT @o+=@i%@,@+=1 END PRINT @o

Brian J

Posted 2017-12-14T01:23:59.903

Reputation: 653

2

4, 67 bytes

4 doesn't have any modulo built in.

3.79960101002029980200300023049903204040310499040989804102020195984

Try it online!

Uriel

Posted 2017-12-14T01:23:59.903

Reputation: 11 708

2

PHP, 61 bytes

-2 bytes for removing the closing tag

<?php $z=fgets(STDIN);for($y=1;$y<$z;$y++){$x+=$z%$y;}echo$x;

Try it online!

NK1406

Posted 2017-12-14T01:23:59.903

Reputation: 739

2

Japt -mx, 3 bytes

N%U

Try it online!

Luis felipe De jesus Munoz

Posted 2017-12-14T01:23:59.903

Reputation: 9 639

2

Brachylog, 9 bytes

⟨gz⟦₆⟩%ᵐ+

Try it online!

Kroppeb

Posted 2017-12-14T01:23:59.903

Reputation: 1 558

1

Husk, 5 bytes

ΣṠM%ḣ

Try it online!

Explanation

ΣṠM%ḣ  -- implicit input x, example: 5
 ṠM%   -- map (mod x) over the following..
    ḣ  -- ..the range [1..x]: [5%1,5%2,5%3,5%4,5%5] == [0,1,2,1,0]
Σ      -- sum: 0+1+2+1+0 == 4

ბიმო

Posted 2017-12-14T01:23:59.903

Reputation: 15 345

1

Pyth, 5 bytes

s%LQS

s%LQS - Full program, inputs N from stdin and prints sum to stdout
s     - output the sum of
 %LQ  - the function (elem % N) mapped over 
    S - the inclusive range from 1..N

Try it online!

Dave

Posted 2017-12-14T01:23:59.903

Reputation: 432

Oh actually I found a different 5 byter than you, didn't read yours correctly – Dave – 2017-12-14T02:59:29.220

1

Perl 5, 23 + 1 (-p) = 24 bytes

//;map$\+=$'%$_,1..$_}{

Try it online!

Xcali

Posted 2017-12-14T01:23:59.903

Reputation: 7 671

1

Neim, 3 bytes

Try It Online!


Explanation:

      # Inclusive range
     # Modulo each element with input
      # Sum the list

LiefdeWen

Posted 2017-12-14T01:23:59.903

Reputation: 3 381

1

APL+WIN, 10 bytes

+/(⍳n)|n←⎕

Prompts for screen input.

Graham

Posted 2017-12-14T01:23:59.903

Reputation: 3 184

1

Pari/GP, 17 bytes

n->sum(m=1,n,n%m)

Try it online!

alephalpha

Posted 2017-12-14T01:23:59.903

Reputation: 23 988

1

Brain-Flak, 70 62 bytes

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

Try it online!

It turns out that the straightforward approach is better. Also, keeping a copy of n on the third stack instead of the first stack saves bytes.

(([{}])<>)                                                      Initialize both stacks with -n
           {                                              }{}   For all k from n down to 1:
             <>(({})<                      >)                   Store -n on third stack
                     <>{(({})){({}())<>}{}}                     Main part of standard modulus program
                                                                (except that the arguments are negative)
                                             <>
            <                                  >                Ignore evaluation of -n
                                                {}[({}())]      Recover n mod k, and decrement k for the next iteration
          (                                                  )  Sum over all iterations and push

Nitrodon

Posted 2017-12-14T01:23:59.903

Reputation: 9 181

Although we already had the modulo challenge... this one seems different. +1. Explanation?

– user202729 – 2017-12-16T03:49:21.467

1

Clean, 39 bytes

Literally just Bruce Forte's Haskell answer, but in Clean.

import StdEnv
@x=sum(map((rem)x)[1..x])

Try it online!

Οurous

Posted 2017-12-14T01:23:59.903

Reputation: 7 916

Well there's pretty much only one (short) way to solve this task.. Btw. using Haskell would save you 17 bytes ;P – ბიმო – 2017-12-18T22:52:12.820

1

Ruby, 23 bytes

->n{eval [*0..n]*"+n%"}

Try it online!

Evaluates a string like 0+n%1+n%2+n%3+n%4+n%5 for n=5.

Lynn

Posted 2017-12-14T01:23:59.903

Reputation: 55 648

0

C, 43 bytes

s,m;f(n){for(s=m=0;m++<n;s+=n%m);return s;}

Try it online!

C (gcc), 38 bytes

s,m;f(n){for(s=m=0;m++<n;s+=n%m);s=s;}

Try it online!

Steadybox

Posted 2017-12-14T01:23:59.903

Reputation: 15 798

That's my best, too: a;i;f(n){a=0;for(i=n;--i;)a+=n%i;return a;} – Toby Speight – 2017-12-19T18:03:44.067

0

J, 9 bytes

-~1#.i.|]

How it works

        ] - the argument 
       |  - mod   
     i.   - list from 0 to argument - 1
  1#.     - sum (base 1 conversion)
-~        - subtract the argument (to get rid of the n mod 0)  

Try it online!

Galen Ivanov

Posted 2017-12-14T01:23:59.903

Reputation: 13 815

0

Pip, 7 bytes

$+a%\,a

Try it online!

         a is 1st cmdline arg
    \,a  Inclusive range from 1 through a
  a%     Take a mod each of those numbers (a%a is 0, so doesn't affect the sum)
$+       Fold on +
         Output (implicit)

DLosc

Posted 2017-12-14T01:23:59.903

Reputation: 21 213

0

MATLAB, 19 bytes

@(n)sum(mod(n,1:n))

Very straightforward, mod calculates n%x for each natural number below n. and sum just sums them all. Test:

@(n)sum(mod(n,1:n))
ans(14)
ans = 

    @(n)sum(mod(n,1:n))
ans =
    31.0000e+000

brainkz

Posted 2017-12-14T01:23:59.903

Reputation: 349

0

Perl 6, 21 16 bytes

{sum $_ «%«(1..$_)}

{sum $_ X%1..$_}

Try it online!

-5 bytes (!) thanks to Brad Gilbert.

Sean

Posted 2017-12-14T01:23:59.903

Reputation: 4 136

This challenge is getting way more submissions than I anticipated. – Nissa – 2017-12-14T18:07:08.920

@StephenLeppik It's because it's easy... xD – Sanchises – 2017-12-15T13:37:49.943

{sum $_ X%1..$_} – Brad Gilbert b2gills – 2017-12-15T17:17:16.910

0

Gaia, 8 bytes

@:…)¦%¦Σ

Try it online!

Giuseppe

Posted 2017-12-14T01:23:59.903

Reputation: 21 077

0

SNOBOL4 (CSNOBOL4), 69 68 bytes

	N =INPUT
A	I =I + 1
	S =LT(I,N) S + REMDR(N,I)	:S(A)
	OUTPUT =S
END

Try it online!

	N =INPUT				;* read in input
A	I =I + 1				;* I is initialized to 0 so this increments it to 1
	S =LT(I,N) S + REMDR(N,I)	 :S(A)	;* similarly with S, add to the remainder
	LT(I,N) :S(A)				;* on success (I < N), goto A
	OUTPUT =S				;* output the sum
END						;* terminate the program

Giuseppe

Posted 2017-12-14T01:23:59.903

Reputation: 21 077

0

Clojure, 38 bytes

#(apply +(for[i(range 1 %)](mod % i)))

Well this is boring, I was hoping #(apply +(map mod(repeat %)(range 1 %))) would have been shorter as mod gets rarely used in map context.

NikoNyrh

Posted 2017-12-14T01:23:59.903

Reputation: 2 361

0

Labyrinth - 45 Characters

?:}}""):={%={{+
     ;        "
@!{{{-{=:}}}::}

Basically, it sets up by taking the input of the number that we are modulo summing. It then starts at one, takes the modulo of that number, and checks if it has reached the target number yet. If it hasn't, take the modulo again and add it to the previous one.

(I left out a lot of stack manipulations if you hadn't guessed, and yes, it actually does output the sum of the modulus up to that number)

C Anderson

Posted 2017-12-14T01:23:59.903

Reputation: 171

0

J, 14 Bytes

M=:+/@:|~}.@i.

How it works:

M=:                 | Define the verb M
            i.      | Get integers in the range [0, input)
         }.@        | Remove the leading 0
       |~           | Take the original input mod each of these integers, making a new array
   +/@:             | Sum this array

Example:

    M 14
31
    M"0 >:i.20    NB. Apply M to each of the integers from 1-20 inclusive
0 0 1 1 4 3 8 8 12 13 22 17 28 31 36 36 51 47 64 61

Bolce Bussiere

Posted 2017-12-14T01:23:59.903

Reputation: 970

0

Common Lisp, 50 47 bytes

(lambda(n)(loop as i from 1 to n sum(mod n i)))

Try it online!

Renzo

Posted 2017-12-14T01:23:59.903

Reputation: 2 260

0

Befunge-93, 36 bytes

p&:10p1>-#1:_$v_g.@
 :p00+g00%\g01<^

Try It Online

Jo King

Posted 2017-12-14T01:23:59.903

Reputation: 38 234

0

Pushy, 13 bytes

&1{:2d%vh;OS#

Try it online!

&1{                 \ Make the stack [n, 1, n]
   :     ;          \ n times do (this consumes last n):
    2d              \    Copy the last two items
      %v            \    Get remainder and put result on stack
        h           \    Increment divisor
          OS        \ Sum the second stack
            #       \ Output the result

FlipTack

Posted 2017-12-14T01:23:59.903

Reputation: 13 242

0

Forth (gforth), 35 bytes

: f 0 over 1 do over i mod + loop ;

Try it online!

Explanation

Loops over all numbers from 1 to n-1 and adds n%i to the sum

Code Explanation

: f            \ start a new word definition
  0 over       \ add a 0 to the stack and place a copy of n above it
  1 do         \ start a counted loop from 1 to n-1
    over i     \ copy n to the the top of the stack and place the loop index above it
    mod +      \ take n%i and add it to the sum
  loop         \ end the counted loop
;              \ end the word definition

reffu

Posted 2017-12-14T01:23:59.903

Reputation: 1 361

0

dc, 31 bytes

[dz%rdz<B]sBd1<B0*0[+z1<C]dsCxp

Try it online!

Assume our input is the only value on the stack. Macro B duplicates top of stack, calculates stack depth, and performs modulo. Runs until stack depth is equal to the input. This works for numbers greater than 1, so we don't run B automatically, but instead only if it's greater than 1 (d1<B). B leaves the input value on top-of-stack, so we multiply by 0. Since 0 is the desired result for an input of 1, this is fine for 1 as well. However, 1 doesn't leave us enough items on the stack to do the initial summation in macro C, so we put another 0 on the stack just in case. Macro C simply adds the two values on top of the stack, and keeps going until the stack only has a single value. Finally, we print.

brhfl

Posted 2017-12-14T01:23:59.903

Reputation: 1 291

0

F#, 35 bytes

let s v=Seq.sumBy(fun x->v%x){1..v}

Try it online!

Pretty straight-forward.

Ciaran_McCarthy

Posted 2017-12-14T01:23:59.903

Reputation: 689

0

Ahead, 21 bytes

I&l@O+K<
~>td-! ntd%~

Try it online!

snail_

Posted 2017-12-14T01:23:59.903

Reputation: 1 982