Write a program to find out the sum of 1 to n number which take minimum time it?

Asked 27-Jan-2023
Viewed 411 times

0

I am writing a procedure for writing code sum of 1 to n numbers. but It takes more seconds to solve it. like 

var a = 1 , var n = 12345678965487512 ,

var sum = 12345678965487513


1 Answer


1

I write some code.

Program 1

using System;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        long n = 1234567896584256, sum = 0;
        for(int i = 1; i <= n; i++)
        {
            sum += i;
        }
        Console.WriteLine("Sum "+ sum);
    }
}

In this example, this problem has been solved. but it takes more and more time to run it. It is not the right way to solve it because in this program time complexity and space complexity are high.

I write code for this question again.

Program 2

using System;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        long n = 10, sum = 0;
        sum = ( n * (n + 1)) / 2;
        Console.WriteLine("Sum "+ sum);
    }
}

In these answers, all program outputs are the same.