- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Programe to find n-th term in series 1 2 2 3 3 3 4
In this problem, we are given an integer N. The task is to find n-th term in series 1 2 2 3 3 3 4….
Let’s take an example to understand the problem,
Input
N = 6
Output
3
Explanation
The series upto nth term is 1, 2, 2, 3, 3, 3, ...
Solution Approach
A simple approach to solve the problem is by using a nested loop. The outer for loop is from 1 to n. And the inner loop is from 1 to i (iterator of outer loop). For each iteration in the inner loop, count the number of elements of the series and return the value of i when count is equal to n.
A more efficient approach to solve the problem is using pattern positions. The elements of the sequence is with their positions in the series are −
Element 1: position 1 Element 2: position 2, 3 Element 3: position 4, 5, 6 Element 4: position 7, 8, 9, 10
For these values, we can create a series using the last position of element in the series which is,
1, 3, 6, 10, 15, 21, 28, ….
x appears in term, 1 + 2 + 3 + … + (x-2) + (x-1)...
This can be generalised as n = x*(x-1)/2
2n = x2 - x => x2 - x - 2n = 0
Solve the equation using formula for solution of quadratic equation,
$$x=1/2*(1+\sqrt{1+8*n)}$$
Program to illustrate the working of our solution,
Example
#include <bits/stdc++.h> using namespace std; int findNthTerm(int n) { int x = (((1) + (double)sqrt(1 + (8 * n))) / 2); return x; } int main(){ int n = 12; cout<<"The series is 1, 2, 2, 3, 3, 3, 4, 4, ...\n"; cout<<n<<"th term of the series is "<<findNthTerm(n); return 0; }
Output
The series is 1, 2, 2, 3, 3, 3, 4, 4, ... 12th term of the series is 5