Author Topic: first & last digits of Fib 2^32  (Read 3478 times)

0 Members and 1 Guest are viewing this topic.

Offline jack

  • Seasoned Forum Regular
  • Posts: 408
    • View Profile
first & last digits of Fib 2^32
« on: March 05, 2022, 05:59:42 pm »
see https://rosettacode.org/wiki/Fibonacci_matrix-exponentiation
due to the limits of double and integer I present a version that computes the first 7 and last 9 digits of fib 2^32
Code: QB64: [Select]
  1. _Title "Fibon"
  2.  
  3. fn = 4294967296 '2^32
  4. m = 1000000000 '10^9
  5.  
  6. 'using the Binet formula for the Fib number  ( ( (1+sqr(5))/2 )^n - ( (1-sqr(5))/2 )^n )/sqr(5)
  7. 'the apprximation of which is the nearest integer of ( ((1+sqr(5))/2)^n )/sqr(5)
  8. 'we take the Log10 of the last expression log10((1+sqr(5))/2)*n)-log10(sqr(5)
  9. '10^FractionalPart is approximately equal the the fib number, the integer part is the exponent
  10. f = ((Log((1 + Sqr(5)) / 2) * fn) - Log(Sqr(5))) / Log(10)
  11. f = f - Fix(f) 'Fractional part
  12. f = 10## ^ f
  13. s = _Trim$(Str$(f))
  14. c = InStr(s, ".")
  15. s = Left$(s, c - 1) + Mid$(s, c + 1)
  16. s = Left$(s, 7)
  17. last9 = fib(fn, m)
  18. Print "the first"; Len(s); " digits of Fibonacci "; fn; " are "; s
  19. Print "the last"; Len(_Trim$(Str$(last9))); " digits of Fibonacci "; fn; " are "; last9
  20.  
  21.     Dim As _Unsigned _Integer64 b, x, y, xx, temp
  22.     Dim As Long i, bit_length
  23.     If k <= 1 Then
  24.         fib = k
  25.         Exit Function
  26.     End If
  27.     b = k
  28.     x = 1: y = 0
  29.     bit_length = Fix(Log(k) / Log(2)) 'Log2(n) giges the highest bit set of an integer
  30.     For i = bit_length - 1 To 0 Step -1
  31.         xx = x * x Mod m
  32.         x = (xx + 2 * x * y) Mod m
  33.         y = (xx + y * y) Mod m
  34.         If b And 1 Then 'if the least significant bit is 1 then
  35.             temp = x
  36.             x = (x + y) Mod m
  37.             y = temp
  38.         End If
  39.         b = b \ 2 'chop off the least significant bit for the next test
  40.     Next
  41.     fib = x
  42.