Count of all possible numbers not exceeding M having suffix N
Last Updated :
10 Jan, 2023
Given two positive integers N and M, the task is to find the count of all possible numbers in the range [1, M], having suffix as N.
Examples:
Input: N = 5, M = 15
Output: 2
Explanation: Only numbers satisfying the conditions are {5, 15}.
Input: N = 25, M = 4500
Output : 45
Naive Approach: The simplest approach is to traverse all integers in the range [1, M] and check if the suffix is N or not.
Time Complexity: O(M)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, following observation needs to be made:
Let N = 5 and M = 100
The Suffix numbers are 5, 15, 25, 35…95, which forms an Arithmetic Progression with
first term = 5, last term = 95, common difference = Base of N (eg: 6 has base 10, 45 has base 100 which is nothing but the exponentiation of the form 10digitsOf(N), where digitsOf(N) = no. of digits present in N.
Therefore, in order to calculate the count of possible numbers in the range [1, M], the following expression needs to be evaluated:
Count of numbers = Number of terms in the series = (tn – a)/d + 1 , where
tn is the last term of the sequence, a is the first term of the sequence, d is the common difference = (ti+1 – ti), i = 1, 2, 3…n-1
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int digitsOf( int num)
{
return to_string(num).size();
}
int count( int a, int tn)
{
int diff = pow (10, digitsOf(a));
return ((tn - a) / diff) + 1;
}
int main()
{
int n, m;
n = 25, m = 4500;
cout << count(n, m);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int digitsOf( int num)
{
return Integer.toString(num).length();
}
static int count( int a, int tn)
{
int diff = ( int )Math.pow( 10 , digitsOf(a));
return ((tn - a) / diff) + 1 ;
}
public static void main (String[] args)
{
int n = 25 , m = 4500 ;
System.out.println(count(n, m));
}
}
|
Python3
def digitsOf(num):
return len ( str (num));
def count(a, tn):
diff = int ( pow ( 10 , digitsOf(a)));
return ((tn - a) / diff) + 1 ;
if __name__ = = '__main__' :
n = 25 ; m = 4500 ;
print ( int (count(n, m)));
|
C#
using System;
class GFG{
static int digitsOf( int num)
{
return num.ToString().Length;
}
static int count( int a, int tn)
{
int diff = ( int )Math.Pow(10, digitsOf(a));
return ((tn - a) / diff) + 1;
}
public static void Main(String[] args)
{
int n = 25, m = 4500;
Console.WriteLine(count(n, m));
}
}
|
Javascript
<script>
function digitsOf(num)
{
return num.toString().length;
}
function count(a, tn)
{
let diff = Math.floor(Math.pow(10, digitsOf(a)));
return Math.floor((tn - a) / diff) + 1;
}
let n = 25, m = 4500;
document.write(count(n, m));
</script>
|
Time Complexity: O(log10(k)) where k is the number of digits in n.
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...