4

My instructions were "for i from 1 to n, do i % m and return the sum. You'll need to get a little clever with performance, since n can be a very large number"

The program below works fine with small numbers. How can I make it efficient with large numbers?

function f(n, m) {
    var summ = 0;

    for (var i = 1; i <= n; i++) {
        summ += i % m;
    }

    return summ;
}
Downgoat
  • 13,771
  • 5
  • 46
  • 69
Wilfredo
  • 137
  • 1
  • 9
  • 8
    Since this sounds like homework, I'm going to give you a hint and see if you can figure out what to do next. Put a `console.log(i % m)` inside your `for` loop and see what it shows for a value of `n` that is at least 5x what `m` is. Here's a demo: http://jsfiddle.net/jfriend00/hjhjyrbe/. – jfriend00 May 17 '15 at 23:21
  • 2
    I agree with @jfriend00, but I will give you one more hint: You don't need a for loop to solve this problem. – Scelesto May 17 '15 at 23:48
  • @jfriend00 It's actually an assignment on codewars.com, so your kind of help is exactly what I want. Unfortunately it worked again with small numbers but not large ones: https://jsfiddle.net/q1g8g6w2/ – Wilfredo May 18 '15 at 00:43
  • @user3696359: Actually we said [no loops](https://en.wikipedia.org/wiki/Triangular_number) at all :-) – Bergi May 18 '15 at 02:00
  • @Bergi, haha yes. my second attempt was based on only jfriend00's comment as i hadn't read the scelesto's advice. – Wilfredo May 18 '15 at 12:31

1 Answers1

0

To see what happening consider the partial sums, first do the sum from 0 to m-1, and the sum from m to 2m - 1, 2m to 3m-1 etc.

m=5;
for(j=0;j<5;++j) {
    partial = 0;
    for(i=j*5;i<j*5+5;++i) {
        partial += i % m;
        console.log( i , partial );
    }
}

To get thing down to one line have a look at Triangular Numbers.

Salix alba
  • 7,536
  • 2
  • 32
  • 38