From d9f34743c281b1f50ba6959ea786f8ef65ab0dc0 Mon Sep 17 00:00:00 2001 From: Preston Baxter Date: Thu, 22 Aug 2024 16:27:40 -0500 Subject: [PATCH] 20 --- cmd/20/main.go | 22 +++++++++++++++++++ pkg/datastructures/bigint.go | 41 ++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 cmd/20/main.go create mode 100644 pkg/datastructures/bigint.go diff --git a/cmd/20/main.go b/cmd/20/main.go new file mode 100644 index 0000000..ffd3b04 --- /dev/null +++ b/cmd/20/main.go @@ -0,0 +1,22 @@ +package main + +import( + "fmt" + ds "euler/pkg/datastructures" +) + +func main() { + bi := ds.NewBigInt(1) + for i := 1; i <= 100; i += 1 { + bi.Multiply(i) + } + + fmt.Printf("%s\n", bi.Stringify()) + + var sum uint64 = 0 + for _, digit := range bi { + sum += uint64(digit) + } + + fmt.Printf("sum: %d\n", sum) +} diff --git a/pkg/datastructures/bigint.go b/pkg/datastructures/bigint.go new file mode 100644 index 0000000..6e30f4c --- /dev/null +++ b/pkg/datastructures/bigint.go @@ -0,0 +1,41 @@ +package datastructures + +import "fmt" + +type BigInt []int + +func NewBigInt(i int) BigInt { + num := i + bi := []int{} + for num > 0 { + bi = append(bi, num % 10) + num = num / 10 + } + + return bi +} + +func (bi *BigInt) Multiply(i int) BigInt { + var carry int = 0 + for index, digit := range *bi { + product := (digit * i) + carry + carry = product / 10 + (*bi)[index] = product % 10 + } + + for carry > 0 { + *bi = append(*bi, carry % 10) + carry = carry / 10 + } + + return *bi +} + +func (bi BigInt) Stringify() string { + out := "" + for i := len(bi)-1; i >= 0; i -= 1 { + out += fmt.Sprintf("%d", bi[i]) + } + + return out +}