Find n-th element in a series with only 2 digits (and 7) allowed in C++


In this problem, we are given an integer N, denoting a series of numbers consisting of 4 and 7 only.

The series is 4, 7, 44, 47, 74, 77, …

The task is to find the n-th element in a series with only 2 digits (and 7) allowed.

Let’s take an example to understand the problem,

Input

N = 4,

Output

47

Explanation

The series is: 4, 7, 44, 47, ….

Solution Approach

A simple solution to the problem is creating the series till Nth number. It’s simple, if the current number’s last digit is 7. Then the last digit of previous and next numbers is 4.

So, we will start from 1st and 2nd numbers and then progress to the next element.

For this, we will create an array series[n+1].

For index series[1] put 4
For index series[2] put 7

Then for successive values till N, find the values for the given index i,

If i is odd, series[i] = series[i/2]*10 + 4
If i is even, series[i] = series[i/2]*10 + 7

After n iterations, return value at series[n].

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int findNthSeriesElement(int N) {
   int series[N+1];
   series[1] = 4;
   series[2] = 7;
   for (int i=3; i<=N; i++) {
      if (i%2 != 0)
         series[i] = series[i/2]*10 + 4;
      else
         series[i] = series[(i/2)-1]*10 + 7;
   }
   return series[N];
}
int main() {
   int N = 9;
   cout<<"The "<<N<<"th element of the array is "<<findNthSeriesElement(N);
   return 0;
}

Output

The 9th element of the array is 474

Updated on: 12-Mar-2021

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements