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.
1def is_self_dividing(num):
2 original = num
3 while num > 0:
4 digit = num % 10
5 if digit == 0 or original % digit != 0:
6 return False
7 num //= 10
8 return True
9
10
11def self_dividing_numbers(left, right):
12 result = []
13 for num in range(left, right + 1):
14 if is_self_dividing(num):
15 result.append(num)
16 return result
17
18
19left, right = 1, 22
20print(self_dividing_numbers(left, right))
This Python function is_self_dividing
checks for self-divisibility. It iterates through each digit to verify divisibility, collecting results in a list.
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.