Count numbers up to N having digit D in its octal representation
Last Updated :
24 Feb, 2022
Given a positive integer N and an integer D representing a digit, the task is to count the numbers in the range[1, N] such that at least one digit in octal representation of the number is d.
Examples:
Input: N = 20, D = 7
Output: 2
Explanation:
The numbers in the range [1, 20] having digit 7 in their octal representation are 7 and 15.
Therefore, the required output is 2.
Input: N = 40, D = 5
Output: 6
Explanation:
The numbers in the range [1, 40] having digit 5 in their octal representation are 5, 13, 21, 29, 37, and 40.
Therefore, the required output is 6
Approach: Follow the steps below to solve the problem:
- Iterate over the range [1, N]. For every ith number check if at least one digit in octal representation of the number is d or not. If found to be true, then increment the count.
- Finally, print the count obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countNumbers( int n, int d)
{
int total = 0;
for ( int i = 1; i <= n; i++) {
int x = i;
while (x > 0) {
if (x % 8 == d) {
total++;
break ;
}
x = x / 8;
}
}
cout << total;
}
int main()
{
int n = 20, d = 7;
countNumbers(n, d);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static void countNumbers( int n, int d)
{
int total = 0 ;
for ( int i = 1 ; i <= n; i++)
{
int x = i;
while (x > 0 )
{
if (x % 8 == d)
{
total++;
break ;
}
x = x / 8 ;
}
}
System.out.println(total);
}
public static void main(String[] args)
{
int n = 20 , d = 7 ;
countNumbers(n, d);
}
}
|
Python3
def countNumbers(n, d):
total = 0
for i in range ( 1 , n + 1 ):
x = i
while (x > 0 ):
if (x % 8 = = d):
total + = 1
break
x = x / / 8
print (total)
if __name__ = = '__main__' :
n , d = 20 , 7
countNumbers(n, d)
|
C#
using System;
class GFG{
static void countNumbers( int n, int d)
{
int total = 0;
for ( int i = 1; i <= n; i++)
{
int x = i;
while (x > 0)
{
if (x % 8 == d)
{
total++;
break ;
}
x = x / 8;
}
}
Console.WriteLine(total);
}
static void Main()
{
int n = 20, d = 7;
countNumbers(n, d);
}
}
|
Javascript
<script>
function countNumbers(n, d)
{
let total = 0;
for (let i = 1; i <= n; i++)
{
let x = i;
while (x > 0)
{
if (x % 8 == d)
{
total++;
break ;
}
x = x / 8;
}
}
document.write(total);
}
let n = 20, d = 7;
countNumbers(n, d);
</script>
|
Time Complexity: O(N * log8N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...