A lot of tech companies ask interesting questions when they hire employees. One of these questions is: How many trailing zeros are there in 1000! (1 × 2 × 3 × .. × 1000).

As you might imagine, the actual result of 1000! is a rather large number, something you can hardly do in your mind, at least unless you’re some kind of savant.

However, there’s a solution you can come up with that doesn’t need a calculator or anything digital. Spoiler alert: There are certain multiplies that give you a zero at the end. Google knows the answer if you’re wondering how to solve this riddle with a paper and a pen.

I’ve been playing around with Google’s language “Go” for a while and wondered if I could solve this riddle using a more brute-force like solution. The code is rather simple, there’s a factorial function I needed to add because the result is too big for a data type like double or int. I then call that function and count the number of zeros using a simple regex pattern. Something you can do when you’re in an interview but it works as well and is also pretty fast.

package main import "fmt" import "math/big" import "regexp" func main() { c := int64(1000) f := big.NewInt(c) s := factorial(f) r := regexp.MustCompile(`[0]+$`) l := r.FindString(s.String()) fmt.Printf("There are %d zeros at the end of %d!\n", len(l), c); } func factorial(n *big.Int) (result *big.Int) { result = new(big.Int) switch n.Cmp(&big.Int{}) { case -1, 0: result.SetInt64(1) default: result.Set(n) var one big.Int one.SetInt64(1) result.Mul(result, factorial(n.Sub(n, &one))) } return } |