Given an integer N, the task is to print all the numbers ≤ N which have their digits as only 1 or 3.
Input: N = 10
Output: 3 1
Input: N = 20
Output: 13 11 3 1
- First check if the number is greater than 0. If yes then proceed further, else program is terminated.
- Check for the presence of digits 1 or 3 at each place of the number.
- If we find 1 or 3 at every place of the number then print the number. Now, check for the next number by using a recursive call for a number one less than the current number.
Below is the implementation of the above approach:
// Loop to iterate through digits
// of the number until every digit
// fulfills the given condition
while ((int)$x > 0 && $flag == 1)
// Get last digit
$digit = $x % 10;
// Updating value of flag to be 0
// if the digit is neither 1 nor 3
if ($digit != 1 && $digit != 3)
$flag = 0;
// Eliminate last digit
$x = $x / 10;
// If N consists of digits 1 or 3 only
if ($flag == 1)
echo $N ;
echo ” “;
// Recursive call for the next number
printNumbers($N – 1);
// Driver code
$N = 20;
// This code is contributed
// by Arnab Kundu
13 11 3 1
Note that the idea of this post to explain a recursive solution there exist a better approach to solve this problem. We can use queue to solve this efficiently. Please refer Count of Binary Digit numbers smaller than N for details of efficient approach.
- Recursive program to print all subsets with given sum
- Recursive program to print formula for GCD of n integers
- Print numbers with digits 0 and 1 only such that their sum is N
- Program to Print Pyramid Pattern using numbers
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Print the last k nodes of the linked list in reverse order | Recursive approach
- Recursive program for prime number
- Recursive Program for Binary to Decimal
- C++ Program for Recursive Bubble Sort
- Recursive program to generate power set
- Recursive program to find all Indices of a Number
- Program to reverse a string (Iterative and Recursive)
- Recursive program to replace all occurrences of pi with 3.14 in a given string
- Recursive program to insert a star between pair of identical characters
- Print all distinct integers that can be formed by K numbers from a given array of N numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.