Find if given number is sum of first n natural numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number num. Our task is to find if the given number is the sum of first n natural numbers. 

 

Problem Description: Here, we need to check whether the given number is the sum of first n natural numbers.

Let’s take an example to understand the problem,

Input: num = 55

Output: yes, 10

Explanation:

55 is the sum of the first 10 natural numbers, 1+2+3+4+5+6+7+8+9+10.

Solution Approach: 

A simple approach to solving the problem is finding the sum of n natural numbers until it becomes equal to or greater than num.

If the sum is equal to num, return n.

If at any value of n the sum becomes greater than n, return -1.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int isNatSum(int num){

   int sum = 0;
   for (int n = 1; sum < num; n++) {
      sum += n;
      if (sum == num)
         return n;
   }
   return -1;
}

int main(){

   int num = 55;
   int n = isNatSum(num);
   if(n == -1)
    cout<<"The value is not sum of natural numbers";
   else
      cout<<"The value is a sum of first "<<n<<" natural numbers";
   return 0;
}

Output −

The value is a sum of first 10 natural numbers

 

This method is good but we can solve the problem more efficiently using the mathematical formula for the sum of n natural numbers.

Sum of first mutual numbers is given by the formula,

sum = n*(n+1)/ 2 

We are given sum and we need to find the value of n,

So we need to create a quadratic equation to find n.

=> 2*Sum = n2 + n

=> n2 + n - 2*sum = 0 , quadratic equation

The solution of this quadratic equation is,

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
#include <math.h>
using namespace std;

int isNatSum(int num){
   
   int n = ( -1+ sqrt (1 + (8*num) ))/2;
   if(ceil(n)==floor(n)){
      return n;
   }
   return -1;
}

int main(){
   
   int num = 55;
   int n = isNatSum(num);
   if(n == -1)
      cout<<"The value is not sum of natural numbers";
   else
      cout<<"The value is a sum of first "<<n<<" natural numbers";
   return 0;
}

Output

The value is a sum of first 10 natural numbers
raja
Published on 22-Jan-2021 13:55:05
Advertisements