gpt4 book ai didi

go - 使用 big.Int int 编写 Pascal 的三角形

转载 作者:IT王子 更新时间:2023-10-29 02:09:08 24 4
gpt4 key购买 nike

我有一些使用 big.Int 的 Pascal 三角形代码。如何添加值?我得到一个错误:

invalid operation: 
PascalTriangle[r - 1][c - 1] + PascalTriangle[r - 1][c]
(operator + not defined on struct)

我正在使用 big.Int 数组,所以我不能使用 big 包中的 Add

func generatePascalTriangle(n int) [][]big.Int {
PascalTriangle := make([][]big.Int, n)
for i := range PascalTriangle {
PascalTriangle[i] = make([]big.Int, n)
}
var one big.Int
one.SetInt64(1)
for r := 0; r < n; r++ {
PascalTriangle[r][0] = one
PascalTriangle[r][r] = one
}
for r := 2; r < n; r++ {
for c := 1; c < r; c++ {
PascalTriangle[r][c] = PascalTriangle[r-1][c-1] + PascalTriangle[r-1][c]
}
}
return PascalTriangle
}

最佳答案

I am using big.Int array so cannot use "Add" from "big" package.


这种说法是错误的。你可以,而且你应该。

例如,

package main

import (
"fmt"
"math/big"
)

func generatePascalTriangle(n int) [][]big.Int {
PascalTriangle := make([][]big.Int, n)
for i := range PascalTriangle {
PascalTriangle[i] = make([]big.Int, n)
}
var one big.Int
one.SetInt64(1)
for r := 0; r < n; r++ {
PascalTriangle[r][0] = one
PascalTriangle[r][r] = one
}
for r := 2; r < n; r++ {
for c := 1; c < r; c++ {
// PascalTriangle[r][c] = PascalTriangle[r-1][c-1] + PascalTriangle[r-1][c]
PascalTriangle[r][c] = *PascalTriangle[r][c].Add(&PascalTriangle[r-1][c-1], &PascalTriangle[r-1][c])
}
}
return PascalTriangle
}

func main() {
t := generatePascalTriangle(7)
for i, r := range t {
for _, n := range r[:i+1] {
fmt.Print(n.String() + " ")
}
fmt.Println()
}
}

Playground :https://play.golang.org/p/KUGsjr8Mon5

输出:

1 
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1

关于go - 使用 big.Int int 编写 Pascal 的三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52379596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com