Given a positive integer N, the task is to find the Nth term of the series
0, 2, 6, 12, 20…till N terms
Examples:
Input: N = 7
Output: 42Input: N = 10
Output: 90
Approach:
From the given series, find the formula for Nth term-
1st term = 1 * (1 – 1) = 0
2nd term = 2 * (2 – 1) = 2
3rd term = 3 * (3 – 1) = 6
4th term = 4 * (4 – 1) = 12
.
.
Nth term = N * (N – 1)
The Nth term of the given series can be generalized as-
TN = N * (N – 1)
Illustration:
Input: N = 7
Output: 42
Explanation:
TN = N * (N – 1)
= 7 * (7 – 1)
= 7 * 6
= 42
Below is the implementation of the above approach-
C++
// C++ program to implement // the above approach #include <iostream> using namespace std; // Function to return // Nth term of the series int nthTerm( int n) { return n * n - n; } // Driver code int main() { // Value of N int N = 7; cout << nthTerm(N) << endl; return 0; } |
C
// C program to implement // the above approach #include <stdio.h> // Function to return // Nth term of the series int nthTerm( int n) { return n * n - n; } // Driver code int main() { // Value of N int N = 7; printf ( "%d" , nthTerm(N)); return 0; } |
Java
// Java program to implement // the above approach import java.io.*; class GFG { public static void main(String[] args) { // Value of N int N = 7 ; System.out.println(nthTerm(N)); } // Function to return // Nth term of the series public static int nthTerm( int n) { return n * n - n; } } |
Python3
# Python code for the above approach # Function to return # Nth term of the series def nthTerm(n): return n * n - n; # Driver code # Value of N N = 7 ; print (nthTerm(N)); # This code is contributed by Saurabh Jaiswal |
C#
using System; public class GFG { // Function to return // Nth term of the series public static int nthTerm( int n) { return n * n - n; } static public void Main() { // Code // Value of N int N = 7; Console.Write(nthTerm(N)); } } // This code is contributed by Potta Lokesh |
Javascript
<script> // JavaScript code for the above approach // Function to return // Nth term of the series function nthTerm(n) { return n * n - n; } // Driver code // Value of N let N = 7; document.write(nthTerm(N) + '<br>' ); // This code is contributed by Potta Lokesh </script> |
42
Time Complexity: O(1) // since no loop is used the algorithm takes up constant time to perform the operations
Auxiliary Space: O(1) // since no extra array is used so the space taken by the algorithm is constant
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!