Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Sum Of First N Numbers

Easy
0/40
Average time to solve is 10m
profile
Contributed by
104 upvotes

Problem statement

You are given an integer ‘n’.


Your task is determining the sum of the first ‘n’ natural numbers and returning it.


Example:
Input: ‘n’ = 3

Output: 6

Explanation: The sum of the first 3 natural numbers is 1 + 2 + 3, equal to 6.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line is an integer ‘n’, denoting the integer.
Output Format:
Return the sum of the first n natural numbers.
Note:-
You don't need to print anything. Just implement the given function.
Sample Input 1:
3
Sample Output 1 :
6
Explanation Of Sample Input 1:
Input: ‘n’ = 3

Output: 6

Explanation: The sum of the first 3 natural numbers is 1 + 2 + 3, equal to 6.
Sample Input 2:
5
Sample Output 2:
15
Explanation of sample output 2:
Input: ‘n’ = 5

Output: 15

Explanation: The sum of the first 5 natural numbers is 1 + 2 + 3 + 4 + 5, equal to 15.
Expected Time Complexity:
The expected time complexity is O(1).
Expected Space Complexity:
The expected space complexity is O(1).
Constraints:
1 <= n <= 10^9
Time Limit: 1 sec
Hint

Can we use a formula to calculate the answer?

Approaches (1)
Maths

We know that the formula to calculate the sum of the first ‘n’ natural numbers is ‘(n) * (n + 1) / 2’. So, what we will do is we will put the given ‘n’ in this formula and store it in a variable. Finally, we will return the answer.

 

The steps are as follows:

 

function sumFirstN(int n):

  1. Initialize a variable ‘ans’.
  2. Assign ‘ans’ to ‘n * (n + 1) / 2’.
  3. Return ‘ans’.
Time Complexity

O(1).


We are calculating the answer in constant operation.
 

Hence, the time complexity is O(1).

Space Complexity

O(1).

 

We are using a variable to keep the answer.


Hence, the space complexity is O(1).

Code Solution
(100% EXP penalty)
Sum Of First N Numbers
All tags
Sort by
Search icon

Interview problems

Most simple CPP solution

long long sumFirstN(long long n) {

    if(n==0)

    return 0;

    

    return sumFirstN(n-1)+n;    

}

70 views
0 replies
0 upvotes

Interview problems

The most effective C++ solution

long long sumFirstN(long long n,long sum = 0) {

// Write your code here.

if(n==0){

return sum;

}

sum = n+sumFirstN(n-1,sum);

}

303 views
1 reply
1 upvote
profile

Interview problems

Easy sol. in JAVA (one test case wasn't passed)

public class Solution {

 

    public static long ans =0;

    public static long sumFirstN(long n) {

        // Write your code here.

        if(n==1) {

            return 1;

        }

        long sum_nm1= sumFirstN(n-1);

        long sum_n = n + sum_nm1;

        return sum_n;

    }

}

137 views
0 replies
0 upvotes

Interview problems

Java soln

public class Solution {

    public static long sumFirstN(long n) {

        int sum=0;

        return printNSum(n,sum);

    }

 

    public static long printNSum(long x, int sum1){

        int p=1;

        while(p<=x){

            sum1=sum1+p;

            p++;

        }

        return sum1;

    }

}

134 views
1 reply
0 upvotes

Interview problems

java code with easy using (am)

import java.util.*;

 

public class Solution {

 

    public static long sumFirstN(long n) {

        long sum=n*(n+1)/2;

 

        return  sum;

    }

    

    public static void main(String args[]){

        Scanner sc=new Scanner(System.in);

        System.out.println(sumFirstN(sc.nextLong()));

    }

}

77 views
0 replies
0 upvotes

Interview problems

With the help of Arithmetic formula

"As we know, the formula for the sum of the first 'n' numbers is sum = n * (n + 1) / 2;

So, if we implement this formula in our code, it would be much more efficient unless it's provided that we do it by some other method. With this approach, the time and space complexity would be O(1)." long long sumFirstN(long long n) {

    // Write your code here.

    long long ans=0;

    ans=n*(n+1)/2;

        return ans;

 

}  

114 views
0 replies
1 upvote

Interview problems

java answer

public static long sumFirstN(long n) {

// Write your code here.

if(n>0){

n=n+sumFirstN(n-1);

}

return n;

}

114 views
0 replies
0 upvotes

Interview problems

C++ (One line)

long long sumFirstN(long long n) {

    // Write your code here.

    return (n*(n +1))/2;

}

279 views
1 reply
2 upvotes

Interview problems

Easy Java Code

public class Solution {

public static long sumFirstN(long n) {

if(n<=0){

return n;

}

return n + sumFirstN(n-1);

}

}

107 views
0 replies
0 upvotes

Interview problems

Python Code - But getting TLE in last testcase

from typing import List

def sumFirstN(n: int) -> int:
	if n == 0: # Base case: when n is 0, return 0
		return 0
	else:
		return n + sumFirstN(n - 1)

python

71 views
0 replies
0 upvotes
Full screen
Console