實作遞迴(7) – x^y (x, y皆整數)
x的y次方,當x, y都是整數時是很基本的題型。
條件歸納
x^y =
\begin{cases}
1, where\ y = 0 \\
x * x^{y-1},\ where\ y > 0\\
\frac{1}{x} * x^{y+1},\ where\ y <= 0\\
\end{cases}Golang
package main
import "fmt"
//遞迴版本x^y
func pow(x, y float64) float64 {
if y == 0 {
return 1
} else if y > 0 {
return x * pow(x, y-1)
} else {
return pow(x, y+1) / x
}
}
func main() {
fmt.Println("input x,y:")
var x, y int
fmt.Scanf("%d,%d", &x, &y)
fmt.Printf("pow(%d, %d) = %f\n", x, y, pow(float64(x), float64(y)))
}
改寫成迭代版本
package main
import "fmt"
//迭代版本x^y
func pow(x, y float64) float64 {
result := x
if y > 0 {
for i := 1; i < int(y); i++ {
result *= x
}
} else {
for i := 0; i >= int(y); i-- {
result /= x
}
}
return result
}
func main() {
fmt.Println("input x,y:")
var x, y int
fmt.Scanf("%d,%d", &x, &y)
fmt.Printf("pow(%d, %d) = %f\n", x, y, pow(float64(x), float64(y)))
}
Filed under: Golang - @ 2021 年 7 月 7 日 上午 10:41
