Tuesday, February 5, 2013

Fibonacci numbers in Basic

Fibonacci numbers can calculated using formula. The resulting numbers can differ from actual ones slightly due to calculation imprecision; to remove this effect, we use function INT which truncates fractional part of the number.



DECLARE FUNCTION FIBONACCI (n)

DIM S AS STRING
S = ""
FOR b = 1 TO 16
    S = S + STR$(INT(FIBONACCI(b) + .1)) + ","
NEXT b
S = S + "..."
PRINT S

FUNCTION FIBONACCI (n)
    num1 = ((1 + SQR(5)) * .5) ^ n
    num2 = ((1 - SQR(5)) * .5) ^ n
    FIBONACCI = (num1 - num2) / SQR(5)
END FUNCTION

0 comments:

Post a Comment