Find if given number is sum of first n natural numbers - GeeksforGeeks

26 Apr, 2021
Given a number s (1 <= s <= 1000000000). If this number is the sum of first n natural number then print, otherwise print -1. Examples: 
Input: s = 10
Output: n = 4
Explanation:
1 + 2 + 3 + 4 = 10

Input: s = 17
Output: n = -1
Explanation:
17 can't be expressed as a 
sum of consecutive from 1.
 Method 1 (Simple):
Start adding numbers from i = 1 to n.
Check if the sum is equal to n, return i.
Else if sum > n, return -1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program for above implementation#include <iostream>using namespace std; // Function to find no. of elements// to be added from 1 to get nint findS(int s){    int sum = 0;     // Start adding numbers from 1    for (int n = 1; sum < s; n++) {        sum += n;         // If sum becomes equal to s        // return n        if (sum == s)            return n;    }     return -1;} // Drivers codeint main(){    int s = 15;    int n = findS(s);    n == -1 ? cout << "-1"            : cout << n;     return 0;}
// Java program for above implementationclass GFG {         // Function to find no. of elements    // to be added from 1 to get n    static int findS(int s)    {        int sum = 0;         // Start adding numbers from 1        for (int n = 1; sum < s; n++)        {            sum += n;                 // If sum becomes equal to s            // return n            if (sum == s)                return n;        }         return -1;    }     // Drivers code    public static void main(String[]args)    {                 int s = 15;        int n = findS(s);        if(n == -1)            System.out.println("-1");        else            System.out.println(n);    }} //This code is contributed by Azkia Anam.
# Python3 program to check if# given number is sum of first n# natural numbers # Function to find no. of elements# to be added from 1 to get ndef findS (s):    _sum = 0    n = 1         # Start adding numbers from 1    while(_sum < s):        _sum += n        n+=1    n-=1         # If sum becomes equal to s    # return n    if _sum == s:        return n    return -1 # Driver codes = 15n = findS (s)if n == -1:    print("-1")else:    print(n) # This code is contributed by "Abhishek Sharma 44".
// C# program for above implementationusing System; class GFG {         // Function to find no. of elements    // to be added from 1 to get n    static int findS(int s)    {        int sum = 0;         // Start adding numbers from 1        for (int n = 1; sum < s; n++)        {            sum += n;                 // If sum becomes equal to s            // return n            if (sum == s)                return n;        }         return -1;    }     // Drivers code    public static void Main()    {                 int s = 15;        int n = findS(s);                 if(n == -1)            Console.WriteLine("-1");        else            Console.WriteLine(n);    }} // This code is contributed by vt_m.
<?php// PHP program for above implementation // Function to find no. of elements// to be added from 1 to get nfunction findS($s){    $sum = 0;     // Start adding numbers from 1    for ($n = 1; $sum < $s; $n++)    {        $sum += $n;         // If sum becomes equal        // to s return n        if ($sum == $s)            return $n;    }     return -1;} // Drivers code$s = 15;$n = findS($s);if($n == -1)echo "-1";elseecho $n; // This code is contributed by Sam007?>
<script> // Javascript program for above implementation    // Function to find no. of elements// to be added from 1 to get n    function findS(s) {        var sum = 0;         // Start adding numbers from 1        for (n = 1; sum < s; n++) {            sum += n;             // If sum becomes equal to s            // return n            if (sum == s)                return n;        }         return -1;    }     // Drivers code              var s = 15;        var n = findS(s);        if (n == -1)            document.write("-1");        else            document.write(n); // This code is contributed by Rajput-Ji </script>
5
Time Complexity: O(s), where s are the no. of consecutive numbers from 1 to sAuxiliary Space: O(1)
Method 2 (Binary Search):
1- Initialize l = 1 and r = n / 2.
2- Apply binary search from l to r.
  a) Find mid = (l+r) / 2
  b) Find sum from 1 to mid using formula 
         mid*(mid+1)/2
  c) If sum of mid natural numbers is equal 
      to n, return mid.
  d) Else if sum > n, r = mid - 1.
  e) Else sum < n, l = mid + 1.
3- Return -1, if not possible.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program for finding s such// that sum from 1 to s equals to n#include <iostream>using namespace std; // Function to find no. of elements// to be added to get sint findS(int s){    int l = 1, r = (s / 2) + 1;     // Apply Binary search    while (l <= r) {         // Find mid        int mid = (l + r) / 2;         // find sum of 1 to mid natural numbers        // using formula        int sum = mid * (mid + 1) / 2;         // If sum is equal to n        // return mid        if (sum == s)            return mid;         // If greater than n        // do r = mid-1        else if (sum > s)            r = mid - 1;         // else do l = mid + 1        else            l = mid + 1;    }     // If not possible, return -1    return -1;} // Drivers codeint main(){    int s = 15;    int n = findS(s);    n == -1 ? cout << "-1"            : cout << n;     return 0;}
// java program for finding s such// that sum from 1 to s equals to nimport java.io.*; public class GFG {         // Function to find no. of elements    // to be added to get s    static int findS(int s)    {        int l = 1, r = (s / 2) + 1;             // Apply Binary search        while (l <= r) {                 // Find mid            int mid = (l + r) / 2;                 // find sum of 1 to mid natural            // numbers using formula            int sum = mid * (mid + 1) / 2;                 // If sum is equal to n            // return mid            if (sum == s)                return mid;                 // If greater than n            // do r = mid-1            else if (sum > s)                r = mid - 1;                 // else do l = mid + 1            else                l = mid + 1;        }             // If not possible, return -1        return -1;    }         // Drivers code    static public void main (String[] args)    {        int s = 15;        int n = findS(s);                 if(n==-1)            System.out.println("-1");        else            System.out.println(n);    }} // This code is contributed by vt_m.
# python program for finding s such# that sum from 1 to s equals to n # Function to find no. of elements# to be added to get sdef findS(s):         l = 1    r = int(s / 2) + 1      # Apply Binary search    while (l <= r) :        # Find mid        mid = int((l + r) / 2)          # find sum of 1 to mid natural numbers        # using formula        sum = int(mid * (mid + 1) / 2)          # If sum is equal to n        # return mid        if (sum == s):            return mid          # If greater than n        # do r = mid-1        elif (sum > s):            r = mid - 1          # else do l = mid + 1        else:            l = mid + 1           # If not possible, return -1    return -1  s = 15n = findS(s)if(n == -1):    print( "-1")else:    print( n ) # This code is contributed by Sam007
// C# program for finding s such// that sum from 1 to s equals to nusing System; public class GFG {         // Function to find no. of elements    // to be added to get s    static int findS(int s)    {        int l = 1, r = (s / 2) + 1;             // Apply Binary search        while (l <= r) {                 // Find mid            int mid = (l + r) / 2;                 // find sum of 1 to mid natural            // numbers using formula            int sum = mid * (mid + 1) / 2;                 // If sum is equal to n            // return mid            if (sum == s)                return mid;                 // If greater than n            // do r = mid-1            else if (sum > s)                r = mid - 1;                 // else do l = mid + 1            else                l = mid + 1;        }             // If not possible, return -1        return -1;    }         // Drivers code    static public void Main ()    {        int s = 15;        int n = findS(s);                 if(n==-1)            Console.WriteLine("-1");        else            Console.WriteLine(n);    }} // This code is contributed by vt_m.
<?php// PHP program for finding// s such that sum from 1// to s equals to n // Function to find no.// of elements to be added// to get sfunction findS($s){    $l = 1;    $r = 1 + (int)$s / 2;      // Apply Binary search    while ($l <= $r)    {         // Find mid        $mid = (int)(($l + $r) / 2);         // find sum of 1 to mid natural        // numbers using formula        $sum = (int)($mid *                    ($mid + 1) / 2);         // If sum is equal to n        // return mid        if ($sum == $s)            return $mid;         // If greater than n        // do r = mid-1        else if ($sum > $s)            $r = $mid - 1;         // else do l = mid + 1        else            $l = $mid + 1;    }     // If not possible,    // return -1    return -1;} // Drivers code$s = 15;$n = findS($s);if($n == -1 )echo "-1";elseecho $n; // This code is contributed by Sam007?>
<script> // Javascript program for finding s such// that sum from 1 to s equals to n public     // Function to find no. of elements    // to be added to get s    function findS(s) {        var l = 1, r = parseInt((s / 2) + 1);         // Apply Binary search        while (l <= r) {             // Find mid            var mid = parseInt( (l + r) / 2);             // find sum of 1 to mid natural            // numbers using formula            var sum = mid * parseInt((mid + 1) / 2);             // If sum is equal to n            // return mid            if (sum == s)                return mid;             // If greater than n            // do r = mid-1            else if (sum > s)                r = mid - 1;             // else do l = mid + 1            else                l = mid + 1;        }         // If not possible, return -1        return -1;    }     // Drivers code        var s = 15;        var n = findS(s);         if (n == -1)            document.write("-1");        else            document.write(n); // This code contributed by Rajput-Ji </script>
5
Time Complexity: O(log n)Auxiliary Space: O(1) 
Method 3: Using Mathematical formula
The idea is to use the formulae of the sum of first N natural numbers to compute the value of the N. Below is the illustration:
⇾ 1 + 2 + 3 + .... N =  S⇾ (N * (N + 1)) /  2 = S⇾ N * (N + 1) = 2 * S⇾ N2  + N  – 2 * S = 0
Therefore, Check if the solution of the quadratic equation is equal to integer or not. If Yes then the solution exists. Otherwise, the given number is not sum of first N natural number.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program of the above// approach #include <bits/stdc++.h> # define ll long long using namespace std; // Function to check if the// s is the sum of first N// natural numberll int isvalid(ll int s){    // Solution of Quadratic Equation    float k=(-1+sqrt(1+8*s))/2;       // Condition to check if the    // solution is a integer    if(ceil(k)==floor(k))        return k;    else      return -1;} // Driver Codeint main(){    int s = 15;       // Function Call    cout<< isvalid(s);    return 0;}
// Java program of the above// approachimport java.util.*; class GFG{     // Function to check if the// s is the sum of first N// natural numberpublic static int isvalid(int s){         // Solution of Quadratic Equation    double k = (-1.0 + Math.sqrt(1 + 8 * s)) / 2;        // Condition to check if the    // solution is a integer    if (Math.ceil(k) == Math.floor(k))        return (int)k;    else      return -1;}     // Driver codepublic static void main(String[] args){    int s = 15;     // Function call    System.out.print(isvalid(s));}} // This code is contributed by divyeshrabadiya07
# Python3 program of the above# approachimport math # Function to check if the# s is the sum of first N# natural numberdef isvalid(s):         # Solution of Quadratic Equation    k = (-1 + math.sqrt(1 + 8 * s)) / 2     # Condition to check if the    # solution is a integer    if (math.ceil(k) == math.floor(k)):        return int(k)    else:        return -1 # Driver Codes = 15 # Function Callprint(isvalid(s)) # This code is contributed by vishu2908
// C# program of the above// approachusing System;class GFG{     // Function to check if the// s is the sum of first N// natural numberpublic static int isvalid(int s){  // Solution of Quadratic Equation  double k = (-1.0 + Math.Sqrt             (1 + 8 * s)) / 2;   // Condition to check if the  // solution is a integer  if (Math.Ceiling(k) ==      Math.Floor(k))    return (int)k;  else    return -1;} // Driver codepublic static void Main(string[] args){  int s = 15;   // Function call  Console.Write(isvalid(s));}} // This code is contributed by Chitranayal
<script> // Javascript program of the above// approach // Function to check if the// s is the sum of first N// natural numberfunction isvalid(s){          // Solution of Quadratic Equation    let k = (-1.0 + Math.sqrt(1 + 8 * s)) / 2;         // Condition to check if the    // solution is a integer    if (Math.ceil(k) == Math.floor(k))        return k;    else      return -1;}// Driver code         let s = 15;      // Function call    document.write(isvalid(s));           </script>
5
Time Complexity: O(1)Auxiliary Space: O(1)
vt_m
Sam007
Roshan Srivastava 1
ajaykr00kj
divyeshrabadiya07
vishu2908
ukasp
Rajput-Ji
sanjoy_62
Binary Search
Mathematical
Misc
Searching
Misc
Searching
Mathematical
Misc
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Modular multiplicative inverse
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
fgets() and gets() in C language