In: Computer Science
Code in Golang:
Write a boolean function called share with one integer parameter which determines whether the sum of the digits in the inputted integer and the inputted integer share a factor other than one. If so, return true, otherwise return false. Examples: 121 sum is 4, so the function returns false 242 sum is 8, so the function returns true
Please refer to the screenshot of the code to understand the indentation of the code and output
Code
package main
import ("fmt")
func share(number int) bool { // function share declaration
var status bool = false // set the return status to false at
first
remainder := 0 // to hold the remainder
sumResult := 0 // to hold the sum of digits of the input
number
var num int = number // passing number to num variable
for num != 0 { // for loop runs till num is not equal to zero
remainder = num % 10 // mod func to find remainder
sumResult += remainder // adding remainder to sum
num = num / 10 // dividing num by 10 to get the next digit
}
var a int
// initialized a to 2 to avoid 1 as common factor
for a = 2; a <= sumResult; a++{ // loop runs till a is less than
or equal to sumResult that we found above
// checks if both sumResult and number have same factors or not
other than one
if(sumResult % a == 0 && number %a ==0){
status = true // set the status to true
break // if condition is true , break the loop
}
}
return status
}
func main() { // main function
var number int // declared variable number
fmt.Print("Enter Number: \n")
fmt.Scanln(&number) // taking input
if (share(number)){ // if function returns true, it prints share a
common factor
fmt.Print("Both number and sum of digits of that number share a
common factor")
}else{
fmt.Print("Do not share a factor")
}
}
Output
Enter Number:
246
Both number and sum of digits of that number share a common factor
Code Screenshot
Output Screenshot