Sponsored
Sponsored
This approach involves iterating over each number within the given range. For each number, extract each digit and check if the number is evenly divisible by that digit. If it passes all checks, the number is self-dividing.
Time Complexity: O(n*m), where n is the range and m is the number of digits in each number.
Space Complexity: O(1) since no extra space is used proportional to input size.
1#include <stdio.h>
2#include <stdbool.h>
3
4bool isSelfDividing(int num) {
5 int original = num, digit;
6 while (num > 0) {
7 digit = num % 10;
8 if (digit == 0 || original % digit != 0) {
9 return false;
10 }
11 num /= 10;
12 }
13 return true;
14}
15
16void selfDividingNumbers(int left, int right) {
17 for (int i = left; i <= right; i++) {
18 if (isSelfDividing(i)) {
19 printf("%d ", i);
20 }
21 }
22}
23
24int main() {
25 int left = 1, right = 22;
26 selfDividingNumbers(left, right);
27 return 0;
28}
This C solution uses a helper function isSelfDividing
to check if each number in the range is a self-dividing number. For each number, we repeatedly extract the last digit and check if it divides the original number evenly. The function returns a boolean indicating if a number is self-dividing.
This approach optimizes the check by making a presumption against numbers containing digit zero immediately. Numbers with digit zero are automatically non-self-divisible. For the rest, we still check each digit, but this could reduce the number of required operations.
Time Complexity: O(n*m), where n is the range and m is reduced due to skipping numbers.
Space Complexity: O(1).
1#include <iostream>
#include <vector>
bool isSelfDividing(int num) {
int original = num, digit;
while (num > 0) {
digit = num % 10;
if (digit == 0 || original % digit != 0) {
return false;
}
num /= 10;
}
return true;
}
std::vector<int> selfDividingNumbers(int left, int right) {
std::vector<int> result;
for (int i = left; i <= right; i++) {
if ((i % 10 != 0) && isSelfDividing(i)) {
result.push_back(i);
}
}
return result;
}
int main() {
int left = 47, right = 85;
std::vector<int> result = selfDividingNumbers(left, right);
for (int number : result) {
std::cout << number << " ";
}
return 0;
}
An optimization in the C++ code checks for numbers that are automatically disqualified (e.g., multiples of ten) due to the zero digit, thus slightly reducing the number of isSelfDividing
calls.