- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find nth number that contains the digit k or divisible by k in C++
Given two positive integers n and k, and we have to find the nth number that contains the digit k or divisible by k. The k will be in range [2 to 9]. So if n and k are 15 and 3 respectively, then output is 33. As the numbers [3, 6, 9, 12, 13, 15, 18, 21, 23, 24, 27, 30, 31, 33] These are those numbers where each element contains the digit k = 3 or divisibility by k and in this nth number is 33. So output is 33.
Check each number that contains k and multiple of k, and count till we get nth element.
Example
#include<iostream> using namespace std; bool hasDigit(int n, int k) { while (n > 0) { int rem = n % 10; if (rem == k) return true; n = n / 10; } return false; } int countNumbers(int n, int k) { for (int i = k + 1, count = 1; count < n; i++) { if (hasDigit(i, k) || (i % k == 0)) count++; if (count == n) return i; } return -1; } int main() { int n = 10, k = 2; cout << "Last number is " << countNumbers(n, k) << " before that the number contains " << k << " and multiple of " << k; }
Output
Last number is 20 before that the number contains 2 and multiple of 2
- Related Articles
- Largest K digit number divisible by X in C++
- C++ Programming for Smallest K digit number divisible by X?
- C++ Program for Smallest K digit number divisible by X?
- C++ Program for Largest K digit number divisible by X?
- C++ Program for the Largest K digit number divisible by X?
- Python Program for Smallest K digit number divisible by X
- Java Program for Largest K digit number divisible by X
- Java Program for Smallest K digit number divisible by X
- Largest number smaller than or equal to N divisible by K in C++
- k-Rough Number or k-Jagged Number in C++
- Subarray Sums Divisible by K in C++
- Find smallest number K such that K % p = 0 and q % K = 0 in C++
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Program to find Nth term divisible by a or b in C++

Advertisements