How to check whether a given number is a Harshad number in Go

1 Answer

0 votes
package main

// Harshad number = is an integer that is divisible by the sum of its digits

import (
	"fmt"
)

func isHarshadNumber(n int) bool {
	sum := 0
	temp := n

	for temp > 0 {
		remainder := temp % 10
		sum += remainder
		temp /= 10
	}

	return n%sum == 0
}

func main() {
	n := 171

	// 1 + 7 + 1 = 9 : 171 % 9 = 0 <- Harshad number

	if isHarshadNumber(n) {
		fmt.Println(n, "is a Harshad number")
	} else {
		fmt.Println(n, "is not a Harshad number")
	}
}



/*
run:

171 is a Harshad number

*/

 



answered Nov 21, 2024 by avibootz
...