

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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++ program to find nth Term of the Series 1 2 2 4 4 4 4 8 8 8 8 8 8 8 8 …
In this problem, we are given an integer N. Our task is to create a program to Find Nth term of series 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8…
Let’s take an example to understand the problem,
Input
N = 7
Output
4
Solution Approach
A simple approach to solve the problem is using a loop to find the term at the nth position. The terms will be updated by doubling after each iteration. And adding it to the term counter.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int calcNthTerm(int N) { int termCounter = 0, termValue = 1; while (termCounter < N) { termCounter += k; termValue *= 2; } return termValue / 2; } int main() { int N = 10; cout<<N<<"th term of the series is "<<calcNthTerm(N); return 0; }
Output
10th term of the series is 8
Efficient Approach
An efficient approach to solve the problem is by finding the general term of the series.
Here, are terms and their last index, 1 -> last index = 1. 2 -> last index = 3. 4 -> last index = 7. 8 -> last index = 15. . . T(N) -> last index = 2*(T(N)) - 1 Also, T(N) is always of a power of 2, i.e. T(N) = 2m 2m lies in the series till the index 2m+1-1.
To find the term we can calculate the value of 2(m) - 1 using N.
This makes 2m - 1 < N.
2m - 1 < N So, m < log2(N + 1)
Program to illustrate the working of our solution,
Example
#include <iostream> #include <math.h> using namespace std; int calcNthTerm(int N) { return ( pow(2, (floor)(log(N + 1) / log(2)) ) ) ; } int main() { int N = 10; cout<<N<<"th term of the series is "<<calcNthTerm(N); return 0; }
Output
10th term of the series is 8
- Related Questions & Answers
- Sum of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n) in C++
- Find the nth term of the given series 0, 0, 2, 1, 4, 2, 6, 3, 8, 4… in C++
- C++ program to find Nth term of the series 0, 2, 4, 8, 12, 18…
- Program to find N-th term of series 0, 0, 2, 1, 4, 2, 6, 3, 8…in C++
- C++ program to find Nth term of the series 1, 8, 54, 384…
- Sum of series 2/3 – 4/5 + 6/7 – 8/9 + …… upto n terms
- 8-bit microprocessors
- 8086 program to reverse 8 bit number using 8 bit operation
- Simulation of 8 to 1 multiplexer
- Java 8 Optional Class
- Attributes in PHP 8
- UTF-8 Validation in C++
- Find the nth term of the series 0, 8, 64, 216, 512,... in C++
- C++ program to get the Sum of series: 1 – x^2/2! + x^4/4! -…. upto nth term
- Interface enhancements in Java 8
Advertisements