If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. I have the following code but the answer do
It should be sum = sum + i
instead of 1
.
Interesting fact of the difference in time between this 2 methods... The second method just calculate only with needed numbers and dont iterate through a loop. Example: 3 * (1+2+3+4...333) (Because 3 * 333 = 999 and 999 < 1000.
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
Calc calculator = new Calc();
long target = 999999999;
sw.Start();
Console.WriteLine("Result: " + (calculator.calcMultipleSumFast(3,target) + calculator.calcMultipleSumFast(5, target) - calculator.calcMultipleSumFast(15, target)));
sw.Stop();
Console.WriteLine("Runtime: " + sw.Elapsed);
Console.WriteLine();
sw.Start();
Console.WriteLine("Result: " + (calculator.calcMultiplesSum(3, 5,1000000000)));
sw.Stop();
Console.WriteLine("Runtime: " + sw.Elapsed);
Console.ReadKey();
}
public class Calc
{
public long calcMultiplesSum(long n1, long n2, long rangeMax)
{
long sum = 0;
for (long i = 0; i < rangeMax; i++)
{
if ((i % n1 == 0) || (i % n2 == 0))
{
sum = sum + i;
}
}
return sum;
}
public long calcMultipleSumFast(long n, long rangeMax)
{
long p = rangeMax / n;
return (n * (p * (p + 1))) / 2;
}
}
Python implementation of the problem. Short, precise and fat.
sum=0
for i in range(1000):
if (i%3==0) or (i%5==0):
sum=sum+i
print sum
int Sum(int N) {
long long c = 0;
N--; //because you want it less than 1000 if less than or equal delete this line
int n = N/3,b = N/5,u = N/15;
c+= (n*(n+1))/2 * 3;
c+= (b*(b+1))/2 * 5;
c-= (u*(u+1))/2 * 15;
return c;
}
Two things:
Change the loop to
for(i=0;i<1000;i++)
And the sum line to
sum=sum+i;
package com.venkat.test;
public class CodeChallenge {
public static void main(String[] args) {
int j, sum=0;
for ( j = 0; j <=1000; j++) {
if((j%5==0)||(j%3==0))
{
sum=sum+j;
}
}
System.out.println(sum);
}
}