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.
1function isSelfDividing(num) {
2 let original = num;
3 while (num > 0) {
4 let digit = num % 10;
5 if (digit === 0 || original % digit !== 0) {
6 return false;
7 }
8 num = Math.floor(num / 10);
9 }
10 return true;
11}
12
13function selfDividingNumbers(left, right) {
14 let result = [];
15 for (let i = left; i <= right; i++) {
16 if (isSelfDividing(i)) {
17 result.push(i);
18 }
19 }
20 return result;
21}
22
23let left = 1, right = 22;
24console.log(selfDividingNumbers(left, right));
This JavaScript solution checks every number in the specified range to see if it is self-dividing. It does this using modulus division and iteration over each digit.
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 <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.