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).
1using System.Collections.Generic;
class SelfDividingNumbers
{
public static 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;
}
public static List<int> SelfDividingNumbersInRange(int left, int right)
{
List<int> result = new List<int>();
for (int i = left; i <= right; i++)
{
if ((i % 10 != 0) && IsSelfDividing(i))
{
result.Add(i);
}
}
return result;
}
static void Main()
{
int left = 47, right = 85;
List<int> result = SelfDividingNumbersInRange(left, right);
Console.WriteLine(string.Join(", ", result));
}
}
Similar to previous examples, the C# solution looks for numbers not ending in zero, thus reducing false eliminations of qualifying candidates through smart filtering before detailed evaluation.