စံကား

11Example programs

Fibonacci numbers

A fast Fibonacci with a generic loop, and the golden ratio with decimals.

Each Fibonacci number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, ... The Recursion page computed them with a function that calls itself twice, which soon gets slow. This version walks forward with a loop and keeps just the last two numbers.

Take the ratio of a Fibonacci number to the one before it, and the answer gets closer and closer to the golden ratio, about 1.618.

စံကား

Expected output

၀
၁
၁
၂
၃
၅
၈
၁၃
၂၁
၃၄
၅၀ ကြိမ်မြောက်
၁၂၅၈၆၂၆၉၀၂၅
ရွှေအချိုး
၁.၆၁၈၀၃၃၉၉၈၅၂၁၈၀၃၃

How it works

  • ဖီဘိုနာချီ keeps two numbers: ရလဒ် (the current one, starting at the default 0) and နောက် (the next one, starting at 1). Each round of the generic loop moves both one step forward. After n rounds, ရလဒ် holds the n-th number and becomes the result with no return statement.
  • လာမည့် ("coming") is declared inside the loop's block, so it is a fresh variable each round.
  • အချိုး ("ratio") converts both numbers to decimals before dividing. Integer division would drop the fraction and print ၁.
  • The 50th number, 12,586,269,025, is far too big for a 32-bit integer, but fits with room to spare in a plain ကိန်းပြည့်.

Hands on

  • Print the 90th Fibonacci number. Then print the 93rd. What happens, and what is the reason? (See Too big for the kind.)