Count all numbers up to N having M as the last digit
Last Updated :
04 May, 2021
Given two positive numbers M and N, the task is to find the count of all numbers having M as the last digit from the range [1, N].
Examples:
Input: M = 5, N = 15
Output: 2
Explanation:
Only 2 numbers(5 and 15) from the range [1, 15] ends with the digit ‘5’.
Input: M = 1, N = 100
Output: 10
Naive Approach: The simplest approach is to iterate over the range 1 to N and check if the last digit is equal to M or not. If found to be true, then increment the count. Finally, print the count obtained.
Time complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is based on the fact that the count of numbers ending with every digit will be the same until the largest multiple of 10 which is less than N (say x). Therefore, its count will be (N / 10). Now, the task is reduced to compute the count of numbers ending with M which are between x and N.
Below are the steps:
- Initialize a variable to store the total count, say total_count.
- Add (N / 10) to the total count.
- Compute x to store the largest multiple of 10 which is less than N using the formula:
x = (N / 10) * 10
- Now, calculate the count of numbers ending with M lying in between x and N.
- Add this count to the total_count. Print the final value of the total_count obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getCount( int N, int M)
{
int total_count = 0;
total_count += (N / 10);
int x = (N / 10) * 10;
if ((N - x) >= M)
{
total_count = total_count + 1;
}
return total_count;
}
int main()
{
int N = 100, M = 1;
cout << getCount(N, M);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int getCount( int N, int M)
{
int total_count = 0 ;
total_count += (N / 10 );
int x = (N / 10 ) * 10 ;
if ((N - x) >= M)
{
total_count = total_count + 1 ;
}
return total_count;
}
public static void main(String[] args)
{
int N = 100 , M = 1 ;
System.out.print(getCount(N, M));
}
}
|
Python3
def getCount(N, M):
total_count = 0
total_count + = N / / 10
x = (N / / 10 ) * 10
if ((N - x) > = M):
total_count = total_count + 1
return total_count
N = 100
M = 1
print (getCount(N, M))
|
C#
using System;
class GFG{
static int getCount( int N, int M)
{
int total_count = 0;
total_count += (N / 10);
int x = (N / 10) * 10;
if ((N - x) >= M)
{
total_count = total_count + 1;
}
return total_count;
}
public static void Main(String[] args)
{
int N = 100, M = 1;
Console.Write(getCount(N, M));
}
}
|
Javascript
<script>
function getCount(N, M){
let total_count = 0
total_count += Math.floor(N / 10)
let x = Math.floor(N / 10) * 10
if ((N - x) >= M){
total_count = total_count + 1
}
return total_count
}
let N = 100
let M = 1
document.write(getCount(N, M))
</script>
|
Time complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...