Open In App

Generate all palindromic numbers less than n

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Find all numbers less than n, which are palindromic. Numbers can be printed in any order.

Examples : 

Input : n = 12
Output : 1, 2, 3, 4, 5, 6, 7, 8, 9, 11
Input : n = 104
Output : 1, 2, 3, 4, 5, 6, 7, 8, 9, 11,
22, 33, 44, 55, 66, 77, 88, 99, 101
[Note that below program prints these numbers
in different order]


Brute Force: We check all the numbers from 1 to n whether its decimal representation is palindrome or not. 

Efficient Approach: We start from 1 and create palindromes of odd digit and even digits up to n. For every number (starting from 1), we append its reverse at end if we need even length palindrome numbers. For odd length palindrome, we append reverse of all digits except last one. 

C++




// A C++ program to generate palindromic numbers
// less than n.
#include <iostream>
using namespace std;
  
// A utility for creating palindrome
int createPalindrome(int input, int b, bool isOdd)
{
    int n = input;
    int palin = input;
  
    // checks if number of digits is odd or even
    // if odd then neglect the last digit of input in
    // finding reverse as in case of odd number of
    // digits middle element occur once
    if (isOdd)
        n /= b;
  
    // Creates palindrome by just appending reverse
    // of number to itself
    while (n > 0)
    {
        palin = palin * b + (n % b);
        n /= b;
    }
    return palin;
}
  
// Function to print decimal palindromic number
void generatePalindromes(int n)
{
    int number;
  
    // Run two times for odd and even length palindromes
    for (int j = 0; j < 2; j++)
    {
        // Creates palindrome numbers with first half as i. 
        // Value of j decided whether we need an odd length
        // of even length palindrome.
        int i = 1;
        while ((number = createPalindrome(i, 10, j % 2)) < n)
        {
            cout << number << " ";
            i++;
        }
    }
}
  
// Driver Program to test above function
int main()
{
    int n = 104;
    generatePalindromes(n);
    return 0;
}


Java




// A Java program to generate palindromic
// numbers less than n.
import java.io.*;
class GFG {
  
// A utility for creating palindrome
static int createPalindrome(int input, int b, int isOdd) {
    int n = input;
    int palin = input;
  
    // checks if number of digits is odd or even
    // if odd then neglect the last digit of input in
    // finding reverse as in case of odd number of
    // digits middle element occur once
    if (isOdd == 1)
        n /= b;
  
    // Creates palindrome by just appending reverse
    // of number to itself
    while (n > 0) {
        palin = palin * b + (n % b);
        n /= b;
    }
    return palin;
}
  
// Function to print decimal 
// palindromic number
static void generatePalindromes(int n) {
    int number;
  
    // Run two times for odd and even 
    // length palindromes
    for (int j = 0; j < 2; j++) {
  
    // Creates palindrome numbers with first 
    // half as i. Value of j decided whether
    // we need an odd length of even length
    // palindrome.
        int i = 1;
        while ((number = createPalindrome(i, 10, j % 2)) < n) {
            System.out.print(number + " ");
            i++;
    }
    }
}
  
// Driver code
public static void main(String[] args) {
    int n = 104;
    generatePalindromes(n);
}
}
// This code is contributed by Anant Agarwal.


Python3




# Generate all palindromic numbers less than n
# A Python program to generate palindromic numbers 
# less than n.
def createPalindrome(inp, b, isOdd):
    n = inp
    palin = inp
   
    # checks if number of digits is odd or even
    # if odd then neglect the last digit of input in
    # finding reverse as in case of odd number of
    # digits middle element occur once
    if (isOdd):
        n = n // b
   
    # Creates palindrome by just appending reverse
    # of number to itself
    while (n > 0):
        palin = palin * b + (n % b)
        n = n // b
    return palin
   
# Function to print decimal palindromic number
def generatePalindromes(n):
   
    # Run two times for odd and even length palindromes
    for j in range(2):
        # Creates palindrome numbers with first half as i. 
        # Value of j decided whether we need an odd length
        # of even length palindrome.
        i = 1
        while (createPalindrome(i, 10, j % 2) < n):
            print (createPalindrome(i, 10, j % 2),end=" ")
            i = i + 1
   
# Driver Program to test above function
n = 104
generatePalindromes(n)
  
#This code is contributed by Afzal Ansari


C#




// A C# program to generate palindromic
// numbers less than n.
using System;
  
class GFG {
  
// A utility for creating palindrome
static int createPalindrome(int input, int b,
                            int isOdd) 
{
    int n = input;
    int palin = input;
  
    // checks if number of digits is odd 
    // or even if odd then neglect the 
    // last digit of input in finding reverse
    // as in case of odd number of digits
    // middle element occur once
    if (isOdd == 1)
        n /= b;
  
    // Creates palindrome by just appending 
    // reverse of number to itself
    while (n > 0)
    {
        palin = palin * b + (n % b);
        n /= b;
    }
    return palin;
}
  
// Function to print decimal 
// palindromic number
static void generatePalindromes(int n) 
{
    int number;
  
    // Run two times for odd and even 
    // length palindromes
    for (int j = 0; j < 2; j++)
    {
  
        // Creates palindrome numbers with first 
        // half as i. Value of j decided whether
        // we need an odd length of even length
        // palindrome.
        int i = 1;
        while ((number = createPalindrome(i, 10, 
                                    j % 2)) < n)
        {
            Console.Write(number + " ");
            i++;
    }
    }
}
  
// Driver Code
public static void Main() 
{
    int n = 104;
    generatePalindromes(n);
}
}
  
// This code is contributed by Nitin Mittal.


Javascript




<script>
    // A Javascript program to generate palindromic
    // numbers less than n.
      
    // A utility for creating palindrome
    function createPalindrome(input, b, isOdd) 
    {
        let n = input;
        let palin = input;
  
        // checks if number of digits is odd 
        // or even if odd then neglect the 
        // last digit of input in finding reverse
        // as in case of odd number of digits
        // middle element occur once
        if (isOdd == 1)
            n = parseInt(n / b, 10);
  
        // Creates palindrome by just appending 
        // reverse of number to itself
        while (n > 0)
        {
            palin = palin * b + (n % b);
            n = parseInt(n / b, 10);
        }
        return palin;
    }
  
    // Function to print decimal 
    // palindromic number
    function generatePalindromes(n) 
    {
        let number;
  
        // Run two times for odd and even 
        // length palindromes
        for (let j = 0; j < 2; j++)
        {
  
            // Creates palindrome numbers with first 
            // half as i. Value of j decided whether
            // we need an odd length of even length
            // palindrome.
            let i = 1;
            while ((number = createPalindrome(i, 10, j % 2)) < n)
            {
                document.write(number + " ");
                i++;
            }
        }
    }
      
    let n = 104;
    generatePalindromes(n);
     
   // This code is contributed by divyesh072019.
</script>


PHP




<?php
// PHP program to generate 
// palindromic numbers less than n.
  
// A utility function for 
// creating palindrome
function createPalindrome($input
                          $b, $isOdd)
{
    $n = $input;
    $palin = $input;
  
    // checks if number of digits is 
    // odd or even if odd then neglect
    // the last digit of input in finding 
    // reverse as in case of odd number 
    // of digits middle element occur once
    if ($isOdd)
        $n = intval($n / $b);
  
    // Creates palindrome by just appending 
    // reverse of number to itself
    while ($n > 0)
    {
        $palin = $palin * $b + intval($n % $b);
        $n = intval($n / $b);
    }
    return $palin;
}
  
// Function to print decimal
// palindromic number
function generatePalindromes($n)
{
    $number = 0;
  
    // Run two times for odd and
    // even length palindromes
    for ($j = 0; $j < 2; $j++)
    {
        // Creates palindrome numbers 
        // with first half as i. Value 
        // of j decided whether we need 
        // an odd length of even length
        // palindrome.
        $i = 1;
        while (($number
                   createPalindrome($i, 10, 
                                    $j % 2)) < $n)
        {
            echo $number . " ";
            $i++;
        }
    }
}
  
// Driver Code
$n = 104;
generatePalindromes($n);
      
// This code is contributed by Sam007
?>


Output

11 22 33 44 55 66 77 88 99 1 2 3 4 5 6 7 8 9 101 

Note that the above program doesn’t print output in sorted order. To print in sorted order, we can store palindromes in a vector and sort it, and don’t forget to use the required header file.

Approach:

  • First, we define a function isPalindrome() which takes an integer n as input and returns a boolean value indicating whether it is palindrome or not.
  • To check if the number is palindrome, we convert it to a string using to_string() function, then we iterate over its first half and compare it with the reversed second half.
  • If the first half is not equal to the reversed second half, the function returns false. Otherwise, it returns true.
  • Next, we define the function generatePalindromes() which takes an integer n as input and generates and prints all palindromic numbers less than n.
  • We iterate over all numbers from 1 to n-1 using a for loop and check if each number is palindrome or not using the isPalindrome() function.
  • If a number is palindrome, we print it using the cout statement.
  • Finally, we call the generatePalindromes() function with the given value of n to print all palindromic numbers less than n.

Below is the implementation of the above approach:

C++




// A C++ program to generate palindromic numbers
// less than n.
  
#include <iostream>
#include <string>
using namespace std;
  
// Function to check if a number is a palindrome
bool isPalindrome(int n) {
    string str = to_string(n);
    int len = str.length();
    for(int i = 0; i < len/2; i++) {
        if(str[i] != str[len-1-i])
            return false;
    }
    return true;
}
  
// Function to generate and print palindromic numbers less than n
void generatePalindromes(int n) {
    for(int i = 1; i < n; i++) {
        if(isPalindrome(i))
            cout << i << " ";
    }
}
  
int main() {
    int n = 104;
    generatePalindromes(n);
    return 0;
}


Java




// A Java program to generate palindromic numbers
// less than n.
  
public class PalindromeGenerator {
    // Function to check if a number is a palindrome
    public static boolean isPalindrome(int n) {
        String str = Integer.toString(n);
        int len = str.length();
        for (int i = 0; i < len / 2; i++) {
            if (str.charAt(i) != str.charAt(len - 1 - i))
                return false;
        }
        return true;
    }
  
    // Function to generate and print palindromic numbers less than n
    public static void generatePalindromes(int n) {
        for (int i = 1; i < n; i++) {
            if (isPalindrome(i))
                System.out.print(i + " ");
        }
    }
  
    public static void main(String[] args) {
        int n = 104;
        generatePalindromes(n);
    }
}


Python3




# A Python program to generate palindromic numbers
# less than n.
  
# Function to check if a number is a palindrome
def is_palindrome(n):
    str_n = str(n)
    length = len(str_n)
    for i in range(length // 2):
        if str_n[i] != str_n[length - 1 - i]:
            return False
    return True
  
# Function to generate and print palindromic numbers less than n
def generate_palindromes(n):
    for i in range(1, n):
        if is_palindrome(i):
            print(i, end=' ')
  
if __name__ == "__main__":
    n = 104
    generate_palindromes(n)


C#




// A C# program to generate palindromic numbers
// less than n.
  
using System;
  
public class PalindromeGenerator
{
    // Function to check if a number is a palindrome
    public static bool IsPalindrome(int n)
    {
        string str = n.ToString();
        int len = str.Length;
        for (int i = 0; i < len / 2; i++)
        {
            if (str[i] != str[len - 1 - i])
                return false;
        }
        return true;
    }
  
    // Function to generate and print palindromic numbers less than n
    public static void GeneratePalindromes(int n)
    {
        for (int i = 1; i < n; i++)
        {
            if (IsPalindrome(i))
                Console.Write(i + " ");
        }
    }
  
    public static void Main(string[] args)
    {
        int n = 104;
        GeneratePalindromes(n);
    }
}


Javascript




// A JavaScript program to generate palindromic numbers
// less than n.
  
// Function to check if a number is a palindrome
function isPalindrome(n) {
    const str = n.toString();
    const len = str.length;
    for (let i = 0; i < Math.floor(len / 2); i++) {
        if (str[i] !== str[len - 1 - i])
            return false;
    }
    return true;
}
  
// Function to generate and print palindromic numbers less than n
function generatePalindromes(n) {
    for (let i = 1; i < n; i++) {
        if (isPalindrome(i))
            process.stdout.write(i + " ");
    }
}
  
const n = 104;
generatePalindromes(n);


Output

1 2 3 4 5 6 7 8 9 11 22 33 44 55 66 77 88 99 101 

Time Complexity: O(n * log10(n)) because we iterate over all numbers from 1 to n-1, which takes O(n) time, and for each number, we need to convert it into a string using to_string() function, which takes O(log10(n)) time, as the number of digits in a number is given by log10(n). Therefore, the overall time complexity is O(n * log10(n)).

Space Complexity: O(log10(n)) because we need to store the string representation of each number, which has a maximum length of log10(n). Therefore, the overall space complexity is O(log10(n)).



 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads