Sum of natural numbers in java

Sum of natural numbers in java

For an integer N, your task is to calculate the sum of first N natural numbers. Input User Task: Since this will be a functional problem, you do not have to worry about input. You just have to complete the function NumberSum() which takes the integer(large value possible) N as a parameter. Constraints: 1 <= N < = 100000000 Output Print the sum of first N natural numbers.

Example

Input 5 

Output 15

Input 1 

Output 1

Solution of Sum of natural numbers :–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
  static void NumberSum(long N)
  {
    long sum=0;
      for(int i=1;i<=N;i++)
        {
          sum=sum+i;
        }
     System.out.println(sum);
  }
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      long N = sc.nextLong();
      NumberSum(N);
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *