forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMagicNumber.dart
57 lines (45 loc) · 1.02 KB
/
MagicNumber.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
A magic number is a number that reduces to 1 after a sequential operation wherein each step we
replace the original number by the sum of its digits until the sum reaches a single digit.
*/
import 'dart:io';
// Function to check if number is a Magic Number
bool isMagicNumber(int num) {
int sum = num;
// iterate until sum is reduces to single digit
while(sum > 9){
int copy = sum;
sum = 0;
// calculating sum of all digits
while(copy > 0){
int digit = copy % 10;
sum += digit;
copy ~/= 10;
}
}
if(sum == 1){
return true;
}
return false;
}
void main() {
print("Enter a number :");
int num = int.parse(stdin.readLineSync()!);
// Call function to check if number is a Magic number
if (isMagicNumber(num)) {
print("$num is a Magic Number");
} else {
print("$num is not a Magic Number");
}
}
/**
Space Complexity O(1)
Time Complexity O(nlog(n))
Sample input/output:
Enter a number :
532
532 is a Magic Number
Enter a number :
123
123 is not a Magic Number
*/