WeakNet Labs

WeakNet Labs is a computer lab I created to learn more about computer science. Security became the number 1 topic over time and programming seems to have taken it's place since. Writing security themed programs, WeakNet Linux and such, has been not only great experience for us, but it helped a few of us land good solid career-like jobs. Read Wikipedia »

WeakNet Linux v3 (Lite)

WeakNet Linux version 3 (Lite) Featured Work

Keep in touch

RSS Feed Twitter Facebook

Subscribe via email

Fibonacci and Tullywacker.

Tuesday, December 15, 2009

Tully has a new blog, http://buffer0verflow.com/ and he posted about a C program that produces the nth Fibonacci number. This made me dig up a piece of code I wrote in PHP a long time ago from the old.html page in http://weaknetlabs.com/BACKUP-NEW/old.html

This is one piece of code I am really proud of. It will only list Fibonacci numbers up to whatever you desire, but it is elegant:

$m = 1; $n = 1; $i = 1; $h = 0;<br /> echo "$m"; echo "$n";<br /> while ($h <= 10) { $i = ($m + $n); echo "$i"; $m = ($n + $i); echo "$m"; $n = ($i + $m); echo "$n"; $h++; } echo "...";

What I think is so elegant about the code is if you look closely you can see that no variable is repeated until all have cycled: "m", "n", and "i." :)

You may want to add "<br /> " to the echo's (if they don't show up as I use the xmp tags{which they did}), so they break a new line separating the integers. Here is the code in action http://weaknetlabs.com/temp/fibonacci.php

Tully's is faster of course since it is compiled.
This sequence is closely related to the Golden ratio and you can learn more about it here:
http://en.wikipedia.org/wiki/Fibonacci_number

1 comments:

  1. tullywacker08 said...

    Mine uses recursion! :P

Post a Comment