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 +}