Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The modulus operator is inefficient. A more faster implementation would be something like this:</p> <pre><code>int multiply2_5(int max) { int i, x2 = 0,x5 = 0,x10 = 0; for(i = 2; i &lt; max; i+=2) x2 += i; // Store all multiples of 2 O(max/2) for(i = 5; i &lt; max; i+=5) x5 += i; // Store all multiples of 3 O(max/5) for(i = 10; i &lt; max; i+=10) x10 += i; // Store all multiples 10; O(max/10) return x2+x5-x10; } </code></pre> <p>In this solution I had to take out multiples of 10 because, 2 and 5 have 10 as multiple so on the second loop it will add multiples of 10 that already been added in the first loop; The three loops combine have O(8/10 max).</p> <p>Another even better solution is if you take a mathematical approach.</p> <p>You are trying to sum all numbers like this 2 + 4 + 6 + 8 ... 10000 and 5 + 10 + 15 +20 + ... 10000 this is the same of having 2 * (1 + 2 + 3 + 4 + … + 5000) and 5 * ( 1 + 2 + 3 + 4 + ... + 2000), the sum of 'n' natural number is (n * (n + 1)) (<a href="http://www.9math.com/book/sum-first-n-natural-numbers" rel="nofollow">source</a>) so you can calculate in a constant time, as it follows:</p> <pre><code>int multiply2_5(int max) { // x = 2 + 4 + 6 + ... = 2 * (1 + 2 + 3 +...) // y = 5 + 10 + 15 + ... = 5 * (1 + 2 + 3 +...) // The sun of n natural numbers is sn = (n (n + 1)) / 2 int x2 = max/ 2; // 2 * ( 1 +2 + 3 … max/2) int x5 = max /5; // 5 * ( 1 +2 + 3 … max/5) int x10 = max/ 10; int sn2 = 0.5 * (x2 * (x2+1)); // (n * (n + 1)) / 2 int sn5 = 0.5 * (x5 * (x5+1)); int sn10 = 0.5 * (x10 * (x10+1)); return (2*sn2) + (5 *sn5) - (10*sn10); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload