如何在Go(Golang)中找出第n个丑陋的数字

91 阅读1分钟

概述

一个丑陋的数字是指其质因数仅限于2,3和5的数字。我们已经看过一个程序,其中给定一个数字n,如果它是一个丑陋的数字,则返回真,否则返回假。下面是该程序的链接:https://golangbyexample.com/ugly-number-golang/

在本教程中,我们将编写一个程序,给定一个数字n,找出第n个丑陋的数字。

例1

Input: 5
Output: 5
Reason: First five ugly numbers are 1, 2, 3, 4, 5 hence 5th ugly number is 5

例2

Input: 20
Output: 36

我们的想法是在这里使用动态编程。我们将跟踪2、3和5的倍数。下一个丑陋的数字总是这三个数字中最小的一个。

程序

下面是同样的程序

package main

import "fmt"

func nthUglyNumber(n int) int {
	dpUgly := make([]int, n)

	dpUgly[0] = 1

	next_multiple_of_2 := 2
	next_multiple_of_3 := 3
	next_multiple_of_5 := 5

	i2 := 0
	i3 := 0
	i5 := 0

	for i := 1; i < n; i++ {
		nextUglyNumber := minOfThree(next_multiple_of_2, next_multiple_of_3, next_multiple_of_5)
		dpUgly[i] = nextUglyNumber

		if nextUglyNumber == next_multiple_of_2 {
			i2++
			next_multiple_of_2 = 2 * dpUgly[i2]
		}

		if nextUglyNumber == next_multiple_of_3 {
			i3++
			next_multiple_of_3 = 3 * dpUgly[i3]
		}

		if nextUglyNumber == next_multiple_of_5 {
			i5++
			next_multiple_of_5 = 5 * dpUgly[i5]
		}

	}

	return dpUgly[n-1]

}

func minOfThree(a, b, c int) int {
	if a < b && a < c {
		return a
	}

	if b < c {
		return b
	}

	return c
}

func main() {
	output := nthUglyNumber(5)
	fmt.Println(output)

	output = nthUglyNumber(20)
	fmt.Println(output)
}

输出

5
36

注意: 请查看我们的Golang高级教程。这个系列的教程是精心设计的,我们试图用例子来涵盖所有的概念。本教程是为那些希望获得专业知识和扎实了解Golang的人准备的 -Golang高级教程