티스토리 뷰

개발/일상

golang big integer

clucle 2020. 12. 23. 23:14

알고리즘 문제를 풀다가 big int가 나와서 golang으로 풀면서 사용 방법을 정리해둔다.

 

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"math/big"
)

var reader = bufio.NewReader(os.Stdin)
var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func init() {
	scanner.Split(bufio.ScanWords)
}

func nextInt() int {
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	return n
}

func main() {
	defer writer.Flush()
	var n, m big.Int

	fmt.Fscan(reader, &n, &m)

	add := new(big.Int)
	add = add.Add(&n, &m)
	fmt.Println("Add : ", add)

	sub := new(big.Int)
	sub = sub.Sub(&n, &m)
	fmt.Println("Sub : ", sub)

	mul := new(big.Int)
	mul = mul.Mul(&n, &m)
	fmt.Println("Mul : ", mul)

	div := new(big.Int)
	div = div.Div(&n, &m)
	fmt.Println("Mul : ", div)

	mod := new(big.Int)
	mod = mod.Mod(&n, &m)
	fmt.Println("Mod : ", mod)
}

실행결과

 

go run algo.go
89789756546545754512374575787454 89789756423121245578787874654
Add :  89879546302968875757953363662108
Sub :  89699966790122633266795787912800
Mul :  8062200369605699570692574596574601014142502722995349097790916
Mul :  1000
Mod :  123424508933586701133454

댓글