Find n-th element in a series with only 2 digits (4 and 7) allowed
Last Updated :
21 Sep, 2022
Consider a series of numbers composed of only digits 4 and 7. First few numbers in the series are 4, 7, 44, 47, 74, 44744,.. etc. Given a number n, we need to find n-th number in the series.
Examples:
Input : n = 2
Output : 7
Input : n = 3
Output : 44
Input : n = 5
Output : 74
Input : n = 6
Output : 77
The idea is based on the fact that the value of last digit alternates in series. For example, if last digit of i-th number is 4, then last digit of (i-1)-th and (i+1)-th numbers must be 7.
We create an array of size (n+1) and push 4 and 7 (These two are always first two elements of series) to it. For more elements we check
1) If i is odd,
arr[i] = arr[i/2]*10 + 4;
2) If it is even,
arr[i] = arr[(i/2)-1]*10 + 7;
At last return arr[n].
C++
#include <bits/stdc++.h>
using namespace std;
int printNthElement( int n)
{
int arr[n+1];
arr[1] = 4;
arr[2] = 7;
for ( int i=3; i<=n; i++)
{
if (i%2 != 0)
arr[i] = arr[i/2]*10 + 4;
else
arr[i] = arr[(i/2)-1]*10 + 7;
}
return arr[n];
}
int main()
{
int n = 6;
cout << printNthElement(n);
return 0;
}
|
Java
class FindNth
{
static int printNthElement( int n)
{
int arr[] = new int [n+ 1 ];
arr[ 1 ] = 4 ;
arr[ 2 ] = 7 ;
for ( int i= 3 ; i<=n; i++)
{
if (i% 2 != 0 )
arr[i] = arr[i/ 2 ]* 10 + 4 ;
else
arr[i] = arr[(i/ 2 )- 1 ]* 10 + 7 ;
}
return arr[n];
}
public static void main (String[] args)
{
int n = 6 ;
System.out.println(printNthElement(n));
}
}
|
Python3
def printNthElement(n) :
arr = [ 0 ] * (n + 1 );
arr[ 1 ] = 4
arr[ 2 ] = 7
for i in range ( 3 , n + 1 ) :
if (i % 2 ! = 0 ) :
arr[i] = arr[i / / 2 ] * 10 + 4
else :
arr[i] = arr[(i / / 2 ) - 1 ] * 10 + 7
return arr[n]
n = 6
print (printNthElement(n))
|
C#
using System;
class GFG
{
static int printNthElement( int n)
{
int []arr = new int [n+1];
arr[1] = 4;
arr[2] = 7;
for ( int i = 3; i <= n; i++)
{
if (i % 2 != 0)
arr[i] = arr[i / 2] * 10 + 4;
else
arr[i] = arr[(i / 2) - 1] * 10 + 7;
}
return arr[n];
}
public static void Main ()
{
int n = 6;
Console.Write(printNthElement(n));
}
}
|
PHP
<?php
function printNthElement( $n )
{
$arr [1] = 4;
$arr [2] = 7;
for ( $i = 3; $i <= $n ; $i ++)
{
if ( $i % 2 != 0)
$arr [ $i ] = $arr [ $i / 2] *
10 + 4;
else
$arr [ $i ] = $arr [( $i / 2) - 1] *
10 + 7;
}
return $arr [ $n ];
}
$n = 6;
echo (printNthElement( $n ));
?>
|
Javascript
<script>
function printNthElement(n) {
var arr = Array(n + 1).fill(0);
arr[1] = 4;
arr[2] = 7;
for ( var i = 3; i <= n; i++) {
if (i % 2 != 0)
arr[i] = arr[i / 2] * 10 + 4;
else
arr[i] = arr[(i / 2) - 1] * 10 + 7;
}
return arr[n];
}
var n = 6;
document.write(printNthElement(n));
</script>
|
Output:
77
Time Complexity: O(n) since using a for loop
Auxiliary Space: O(n) for creating an array of size N + 1.
Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...