Count of N digit palindromic numbers divisible by 9
Given an integer N, the task is to count the number of N digit palindromic numbers containing digits from 1 to 9 and divisible by 9.
Examples:
Input: N = 1
Output: 1
Explanation:
Only 9 is 1 digit number which is palindrome and divisible by 9.
Input: N = 3
Output: 9
Explanation:
Three digit numbers those are palindrome and divisible by 9 are –
{171, 252, 333, 414, 585, 666, 747, 828, 999}
Approach: The key observation in the problem is if the number is divisible by 9 then sum of digits of the number is also divisible by 9. Therefore, the problem can be segregated on the basis of its parity.
- If N is odd: We can put any number from 1 to 9 in position 1 to (N-1)/2, Similarly, the other digits are chosen in reverse order to form palindromic number and the middle element is chosen on to form the sum of digits divisible by 9. Therefore, there are 9 choices for each position of (N-1)/2 digits of the number due to which the count of such number will be:
Count of N-digit Palindromic numbers =
9(N-1)/2
- If N is even: We can put any number from 1 to 9 at the position from 1 to (N-2)/2, Similarly, the other digits are chosen in reverse order to form palindromic number and the middle element is chosen on to form the sum of digits divisible by 9. Therefore, there are 9 choices for each position of (N-2)/2 digits of the number due to which the count of such number will be:
Count of N-digit Palindromic numbers =
9(N-2)/2
C++
#include <bits/stdc++.h>
using namespace std;
int countPalindromic( int n)
{
int count;
if (n % 2 == 1) {
count = pow (9, (n - 1) / 2);
}
else
{
count = pow (9, (n - 2) / 2);
}
return count;
}
int main()
{
int n = 3;
cout << countPalindromic(n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countPalindromic( int n)
{
int count;
if (n % 2 == 1 )
{
count = ( int ) Math.pow( 9 , (n - 1 ) / 2 );
}
else
{
count = ( int ) Math.pow( 9 , (n - 2 ) / 2 );
}
return count;
}
public static void main(String[] args)
{
int n = 3 ;
System.out.println(countPalindromic(n));
}
}
|
Python3
def countPalindromic(n):
count = 0
if (n % 2 = = 1 ):
count = pow ( 9 , (n - 1 ) / / 2 )
else :
count = pow ( 9 , (n - 2 ) / / 2 )
return count
n = 3
print (countPalindromic(n))
|
C#
using System;
class GFG{
static int countPalindromic( int n)
{
int count;
if (n % 2 == 1)
{
count = ( int ) Math.Pow(9, (n - 1) / 2);
}
else
{
count = ( int ) Math.Pow(9, (n - 2) / 2);
}
return count;
}
public static void Main()
{
int n = 3;
Console.Write(countPalindromic(n));
}
}
|
Javascript
<script>
function countPalindromic(n)
{
var count;
if (n % 2 == 1) {
count = Math.pow(9, (n - 1) / 2);
}
else
{
count = Math.pow(9, (n - 2) / 2);
}
return count;
}
var n = 3;
document.write( countPalindromic(n));
</script>
|
Time Complexity: O(log9n)
Auxiliary Space: O(1)
Last Updated :
05 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...