Find the sum of all the multiples of 3 or 5 below 1000

前端 未结 16 949
时光说笑
时光说笑 2020-12-10 16:41

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

16条回答
  •  抹茶落季
    2020-12-10 17:01

    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;
        }
    }
    

提交回复
热议问题