Repeated sum of first N natural numbers
Last Updated :
18 Mar, 2022
Given two integers N and K, the task is to find the sum of first N natural numbers then update N as the previously calculated sum. Repeat these steps K times and finally print the value of N.
Examples:
Input: N = 2, K = 2
Output: 6
Operation 1: n = sum(n) = sum(2) = 1 + 2 = 3
Operation 2: n = sum(n) = sum(3) = 1 + 2 + 3 = 6
Input: N = 3, K = 2
Output: 21
Approach: Find the sum of first N natural numbers using the formula (N * (N + 1)) / 2 then update N with the calculated sum. Repeat these steps exactly K times and print the final value of N.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int sum( int n)
{
int sum = (n * (n + 1)) / 2;
return sum;
}
int repeatedSum( int n, int k)
{
for ( int i = 0; i < k; i++) {
n = sum(n);
}
return n;
}
int main()
{
int n = 2, k = 2;
cout << repeatedSum(n, k);
return 0;
}
|
Java
class GFG
{
static int sum( int n)
{
int sum = (n * (n + 1 )) / 2 ;
return sum;
}
static int repeatedSum( int n, int k)
{
for ( int i = 0 ; i < k; i++)
{
n = sum(n);
}
return n;
}
public static void main (String[] args)
{
int n = 2 , k = 2 ;
System.out.println(repeatedSum(n, k));
}
}
|
Python3
def sum (n):
sum = (n * (n + 1 )) / / 2
return sum
def repeatedSum(n, k):
for i in range (k):
n = sum (n)
return n
n = 2
k = 2
print (repeatedSum(n, k))
|
C#
using System;
class GFG
{
static int sum( int n)
{
int sum = (n * (n + 1)) / 2;
return sum;
}
static int repeatedSum( int n, int k)
{
for ( int i = 0; i < k; i++)
{
n = sum(n);
}
return n;
}
public static void Main (String[] args)
{
int n = 2, k = 2;
Console.WriteLine(repeatedSum(n, k));
}
}
|
Javascript
<script>
function sum(n) {
var sum = (n * (n + 1)) / 2;
return sum;
}
function repeatedSum(n , k) {
for (i = 0; i < k; i++) {
n = sum(n);
}
return n;
}
var n = 2, k = 2;
document.write(repeatedSum(n, k));
</script>
|
Time Complexity: O(k)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...