A number can be a Perfect number if the sum of positive divisors excluding the number itself equals a given number. For instance 6 is a perfect number (Sum of 6 Divisors are: 1 + 2 + 3 = 6).
This Go program to find the Perfect Number uses for loop (for i := 1; i < perfNum; i++) and If statement (if perfNum%i == 0) to find the sum of the given number’s positive divisors. After the for loop, we used the If else statement (if perfNum == perfsum) to check whether the divisors’ sum equaled to a given number. If True, it is a perfect number; otherwise, not perfect.
package main import "fmt" func main() { var perfNum, perfsum int perfsum = 0 fmt.Print("Enter the Number to find the Perfect = ") fmt.Scanln(&perfNum) for i := 1; i < perfNum; i++ { if perfNum%i == 0 { perfsum = perfsum + i } } if perfNum == perfsum { fmt.Println(perfNum, " is a Perfect Number") } else { fmt.Println(perfNum, " is Not a Perfect Number") } }
SureshMac:Goexamples suresh$ go run perfect1.go
Enter the Number to find the Perfect = 6
6 is a Perfect Number
SureshMac:Goexamples suresh$ go run perfect1.go
Enter the Number to find the Perfect = 22
22 is Not a Perfect Number
Go Program to find the Number is Perfect using Functions
package main import "fmt" var perfsum int = 0 func perfectNum(perfNum int) int { for i := 1; i < perfNum; i++ { if perfNum%i == 0 { perfsum = perfsum + i } } return perfsum } func main() { var perfNum int fmt.Print("Enter the Number to find the Perfect = ") fmt.Scanln(&perfNum) perfsum = perfectNum(perfNum) if perfNum == perfsum { fmt.Println(perfNum, " is a Perfect Number") } else { fmt.Println(perfNum, " is Not a Perfect Number") } }
SureshMac:Goexamples suresh$ go run perfect2.go
Enter the Number to find the Perfect = 28
28 is a Perfect Number
SureshMac:Goexamples suresh$ go run perfect2.go
Enter the Number to find the Perfect = 250
250 is Not a Perfect Number
This Golang program will find and print the Perfect numbers between the minimum and maximum limit.
package main import "fmt" func main() { var perfNum, perfMin, perfMax, perfsum int perfsum = 0 fmt.Print("Enter the Minimum and Maximum limit of Perfect Numbers = ") fmt.Scanln(&perfMin, &perfMax) for perfNum = perfMin; perfNum <= perfMax; perfNum++ { perfsum = 0 for i := 1; i < perfNum; i++ { if perfNum%i == 0 { perfsum = perfsum + i } } if perfNum == perfsum { fmt.Print(perfNum, "\t") } } }