Fibonacci sequence: Difference between revisions
→BASIC: moved array example to its own subsection
(→BASIC: rules abuse; see the talk page) |
(→BASIC: moved array example to its own subsection) |
||
Line 234:
-1</pre>
===Recursive===▼
<lang qbasic>▼
FUNCTION recFib (n)▼
IF (n < 2) THEN▼
recFib = n▼
ELSE▼
recFib = recFib(n - 1) + recFib(n - 2)▼
END IF▼
END FUNCTION▼
</lang>▼
===Array (Table) Lookup===
This uses a pre-generated list, requiring much less run-time processor usage. (Since the sequence never changes, this is probably the best way to do this in "the real world". The sam applies to other sequences like prime numbers, and numbers like pi and e.)
<lang qbasic>DATA 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765
DATA 10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269
Line 251 ⟶ 263:
PRINT fibNum(42)
'*****sample inputs*****
▲</lang>
▲===Recursive===
▲<lang qbasic>
▲FUNCTION recFib (n)
▲ IF (n < 2) THEN
▲ recFib = n
▲ ELSE
▲ recFib = recFib(n - 1) + recFib(n - 2)
▲ END IF
▲END FUNCTION
</lang>
|