forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
armstrong_number.go
76 lines (66 loc) · 1.7 KB
/
armstrong_number.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Golang Program to check whether a given number is an Armstrong number or not
/*
In recreational number theory, an Armstrong number (also known as narcissistic number)
is a number that is equal to the sum of its own digits, each raised to the power of
the total number of digits.
For example, in the case of 3 digit numbers,
153 is an Armstrong number as 153 = 1*1*1 + 5*5*5 + 3*3*3
*/
package main
import (
"fmt"
"strconv"
)
func main() {
// taking an 'n' digit number as input
var number int
fmt.Print("\n Enter a number : ")
fmt.Scan(&number)
// displaying results after calling isArmstrong()
if isArmstrong(number) {
fmt.Printf(" %d is an Armstrong number", number)
} else {
fmt.Printf(" %d is NOT an Armstrong number", number)
}
}
// function to check whether a number is Armstrong or not
func isArmstrong(number int) bool {
sum := 0
digit := 0
copyNum := number
/* getting the number of digits of the integer by
converting it to a string and finding its length */
numberOfDigits := len(strconv.Itoa(number))
for {
// discarding negative integers
if copyNum <= 0 {
break
}
temp := 1
// extracting last digit
digit = copyNum % 10
// raising it to the power of number of digits
for i := 0; i < numberOfDigits; i++ {
temp = temp * digit
}
// storing the resulting number in sum
sum += temp
copyNum = copyNum / 10
}
// returning true if the number is equal to sum
return number == sum
}
/*
Time Complexity = O(log(n))
Space Complexity = O(1)
Sample inputs and outputs:
i/o 1 -
Enter a number: 153
153 is an Armstrong number.
i/o 1 -
Enter a number: 369
369 is NOT an Armstrong number.
i/o 3 -
Enter a number: 370
370 is an Armstrong number.
*/