Advertisement
Pug_coder

FibonacciMatrix

Mar 15th, 2021
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "math/big"
  6. )
  7.  
  8. func fib(n int) *big.Int {
  9. a := big.NewInt(1)
  10. b := big.NewInt(1)
  11. c := big.NewInt(1)
  12. rc := big.NewInt(0)
  13. d := big.NewInt(0)
  14. rd := big.NewInt(1)
  15. for ; n > 0;{
  16. if n % 2 != 0 {
  17. tc := rc
  18. //rc = rc * a + rd * c
  19. rc1 := new(big.Int).Add(new(big.Int).Mul(rc,a) , new(big.Int).Mul(rd,c))
  20. rc = rc1
  21. //rd = tc * b + rd * d
  22. rd1 := new(big.Int).Add(new(big.Int).Mul(tc, b) , new(big.Int).Mul(rd, d))
  23. rd = rd1
  24. }
  25. ta := a
  26. //fmt.Println("ta = ",ta)
  27. tb := b
  28. //fmt.Println("tb = ",tb)
  29. tc := c
  30. //fmt.Println("tc = ",tc)
  31. //a = a*a + b*c
  32. a = new(big.Int).Add(new(big.Int).Mul(a, a), new(big.Int).Mul(b, c))
  33. //fmt.Println("a = ",a)
  34. //b = ta*b + b*d
  35. b= new(big.Int).Add(new(big.Int).Mul(ta,b) , new(big.Int).Mul(b,d))
  36. //c = c*ta + d*c
  37. //fmt.Println("b = ",b)
  38. c = new(big.Int).Add(new(big.Int).Mul(c,ta) , new(big.Int).Mul(d,c))
  39. //d = tc*tb+ d*d
  40. //fmt.Println("c = ",c)
  41. d = new(big.Int).Add(new(big.Int).Mul(tc,tb) , new(big.Int).Mul(d,d))
  42. //fmt.Println("d = ",d)
  43. n >>= 1
  44.  
  45. }
  46. return rc
  47. }
  48.  
  49.  
  50. func main(){
  51. var n int
  52. fmt.Scan(&n)
  53. fmt.Print(fib(n))
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement