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.
1using System;
2using System.Collections.Generic;
3
4class SelfDividingNumbers
5{
6 public static bool IsSelfDividing(int num)
7 {
8 int original = num, digit;
9 while (num > 0)
10 {
11 digit = num % 10;
12 if (digit == 0 || original % digit != 0)
13 {
14 return false;
15 }
16 num /= 10;
17 }
18 return true;
19 }
20
21 public static List<int> SelfDividingNumbersInRange(int left, int right)
22 {
23 List<int> result = new List<int>();
24 for (int i = left; i <= right; i++)
25 {
26 if (IsSelfDividing(i))
27 {
28 result.Add(i);
29 }
30 }
31 return result;
32 }
33
34 static void Main()
35 {
36 int left = 1, right = 22;
37 List<int> result = SelfDividingNumbersInRange(left, right);
38 Console.WriteLine(string.Join(", ", result));
39 }
40}
The C# implementation uses a list to store numbers that qualify as self-dividing. The solution employs a while
loop to check each digit’s divisibility.
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
This C solution skips numbers divisible by 10 entirely, focusing on the rest to identify self-dividing numbers, slightly optimizing computations by reducing unnecessary checks.