Sunday, August 14, 2016

The Fibonacci Sequence in Six (plus) Languages

The Fibonacci Sequence in Six (plus) Languages
Python, C, Java, Node.js, Javascript, Powershell

I wanted to write a blog post that shows how to generate the Fibonacci sequence (0;1;1;2;3;5;8;13;21;34;55;...) in ten languages. Then I realized I would have to relearn some older language's syntax and that would mess up my current knowledge. So this is now down to five languages.

You should see output like:
First 10 Fibonacci numbers
1
2
3
5
8
13
21
34
55

Some of the scripts put the numbers on one line.

I had to encode all the less than and greater than's to keep the browser from interpreting them.



Python 2
I ran this in my Mac terminal with: python fibo.py

# fibonacci series generator for the first 10 numbers

# Seeds 0 and 1

x=0
y=1

print "First 10 Fibonacci numbers"

for i in range(1,10):
  t = x + y
  x = y
  y = t
  print t






Python 3
Then I rewrote it all in Python 3, and it uses fancy tuple unpacking which avoids needing a temporary variable. Putting in the end=" " keeps the series all on one line.

# fibonacci series generator for the first 10 numbers
# using tuple unpacking
# for Python 3

# Seeds 0 and 1

x=0
y=1

print ("First 10 Fibonacci numbers")

for i in range(1,10):
  print (y, end=" ")
  x, y = y, (x+y)





C
You need to compile this with a C compiler.

#include <stdio.h>

int main () 
{
  int x=0;
  int y=1;
  int i,t;
  printf ("First 10 Fibonacci numbers\n");

  for (i=0;i<10;i++)
  {
    t = x + y;
    x = y;
    y = t;
    printf ("%d ",t); 
  }
  printf("\n");

  return (0);
}



Java
Probably should have it be more object oriented, but that doesn't save any lines in this case.
You do have to have the Java dev kit installed on your system.
#include <stdio.h>

int main () 

{
  int x=0;
  int y=1;
  int i,t;
  printf ("First 10 Fibonacci numbers\n");
  for (i=0;i<10;i++)
  {
    t = x + y;
    x = y;
    y = t;
    printf ("%d ",t); 
  }
  printf("\n");
  return (0);
}



Node.js
Node is kind of like Javascript without needing a browser. It's a nice, refreshing language.
You have to have Node locally installed and then run it in the terminal with 
node fibo.js.

fibo.js:

 x=0
 y=1
 console.log ("First 10 Fibonacci numbers.")
 for (i=0;i<10 font="" i="" nbsp="">
 {
     t = x + y
     x = y
     y = t
     console.log (t);
 } 



Javascript Load this one into a browser. Getting this to even show up in the browser was a pain. Had to remove all the html and script tags. Tag: means the tag inside of angle brackets. Close tag: means use the closing tag which is the tag proceeded with a forward slash.
Tag: html
Tag: body
Tag: script
 x=0
 y=1
 document.write("First 10 Fibonacci numbers.")
 for (i=0;i<10;i++) 
 {
     t = x + y
     x = y
     y = t
     document.write(t," ");
 } 

Close tag: script
Close tag: body
Close tag: html


Powershell
$x = 0
$y = 1

$enditer = 10

for ($i=0;$i -lt $enditer;$i++) 
{
  $t = $x + $y
  write-host $t " "
  $x = $y
  $y = $t
}

write-host "End of series"

50 comments:

Sharon Minsuk said...

Object oriented, schmobject oriented. There's a time and a place for everything, and this was not that. ;-)

Getting Javascript to show up: try substituting '<' for '<' to be able to make tags visible. Then wrap the whole thing with the 'pre' tag to get all your whitespace to show up without all those pesky  .

Sharon Minsuk said...

Bah. That was supposed to say, try substituting the character entity in place of '<' ! Blogger turned my character entity back into a <. :-)

Let's see if this works:

&<
&lt;

Ellen said...

I had to take out all the html in those sections and use the pre tag, but I have to remove all the html first.

Nathan William said...

Geography is a subject of learning and each student need to have sound knowledge into it. However, majority of the students face some issues in completing their assignments and end up scoring less marks in those. So, are you in need of a perfectly written Geography assignment that can fetch you highest scores? Here, at Myassignmenthelp.com you will get all kinds of solutions to your problems. So stop worrying now and get instant do my homework online service from professional experts of our website. Not only our essay assistance experts are highly experienced, but also they hold either a master’s or doctorate degree from eminent universities of UK and USA.

Assignment Help said...

Your article is so convincing that I never stop myself from appreciating this. Thank you for posting this. If you are looking for Online Assignment Help online services and if you want to boost your marks without putting your efforts. If you have time issues, do contact online assignment writing service provider and receive the best assignments as per your job requirements.

Olivia Crew said...

You had me engaged by reading and you know what? I want to read more about that. That's what's used as an amusing post.
read more:- Assignment Help Sydney

James Charlie said...

The blog on psychology is certainly resourceful, and well written. If you have been unable to find optimum time to conduct further research, you can head to seeking professional services at myassignmenthelpau.com. Feel free to explore the services and attain Assignment Help Ottawa.

Sam Smith said...

I have bookmarked your site for regular checkup. Did you know that One of the most recommended pieces of home exercise equipment is a treadmill? This is because it offers an effective aerobic workout for users at any skill or conditioning level. Professional runners and first-time exercisers alike can benefit from this machine, but electric models commonly found in commercial gyms can be prohibitively expensive, as well as intimidating to beginners. Learn more on Reviews on Manual Treadmills .

newassignmenthelpaustralia said...

Get the best project management assignment help from Australia by experts at affordable prices. Get the best project management assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

newassignmenthelpaustralia said...

Get the best python assignment help from Australia by experts at affordable prices. Get the best python assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

newassignmenthelpaustralia said...

Get the best business law assignment help from Australia by experts at affordable prices. Get the best business law assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

newassignmenthelpaustralia said...

Get the best electrical assignment help from Australia by experts at affordable prices. Get the best electrical assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

The Assignment House said...

Thanks for sharing. I found a lot of interesting information here. A really good post, very thankful and hopeful that you will write many more posts like this one.

assignment help
assignment help 4 me online
best paper checker
order essay online
turabian citation

assignmentauthors said...

Children are freer to talk to their Mrs. D.S than Mr. G.S. Most concerns are presented to the mother who would speak to their father hire an essay writer

James Smith said...

Enjoy the bulldog campground sturgis sd with easy trail access to 700+ miles of motorized trails just behind BCC. If you haven't hit the trails before DON'T WORRY we have folks that would gladly take you along and show you some fo the trails.

ella said...

Thanks for the amazing information. I really love to have more information like this soon.

netgear router login |

WordPress Login

Assignment Writing Help said...

Are you looking for Assignment Help online? We are here to provide you the best assignment help in Australia at affordable prices. NAH also provides different types of Assignments like Cheap assignment help, Nursing assignment help, Assignment Help Melbourne, Assignment Help Sydney etc.
visit us: https://www.newassignmenthelpau.com/

Patrika Jones said...

Looking for ways to set up your new router on your local network visit us at 192.168.1.1 we might be able to help you with that.
Looking for ways to set up your new router on your local network visit us at 192.168.0.1 we might be able to help you with that.

Article Piece said...

During a tarot meditation your consciousness will be opened to the infinite possibilities of each card. You will be guided by your inner wisdom to see things

Anonymous said...

Office is a versatile range of products that help you to complete a task with less effort, complete office.com/setup procedure. As soon as you are done with the download and setup, the previous step is to trigger the Office Subscription.
office.com/setup | norton.com/setup

customhouzz said...

Buy Sofa cum bed wooden online from customhouzz at an affordable price. Best sofa cum bed in India. This sofa cum bed are specially designed for less space living room and bedrooms to optimize less space at its full.

ella said...

Thankful to you for giving to us, I additionally reliably increase some new helpful information from your post. I always like to read quality content having accurate information regarding the subject.

Facebook Login

ij.start.cannon

amazon.com/code

ella said...

I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

FMovies

FMovies

Web Assignment Help said...

It is really helpful for readers who are looking for online assignment help. I also work in the same area and provide assignment help to students for various subjects. Most of my students are from parts of the UK, USA, India, and Singapore. Our team of professors are from reputed Colleges. Visit our website to know our areas of expertise and let us know if we can be of help. Also Read: how many pages is 1000 words, how many pages is 2000 words

Isabell Kiral said...

All these programming languages are very helpful for us and through these, we can make our future secure and safe. You should learn these and earn a lot of money. Cheap dissertation writing service.

Arif said...

This article has brought to an end my long internet search thank you. This ground-breaking book is an indispensable practical guide to the successful execution of research with particular attention to data analysis to arrive at indispensable findings, conclusions, and generalizations. Studying this book endows you with the requisite mastery knowledge for personally applying the most appropriate statistical tests accurately, swiftly, effortlessly and pleasurably in situations of data analysis. It is a most clearly written modern and practical book with simple, direct, easy-to-understand and highly motivating information. Read more on SPSS Research Paper

John Malcova said...


Amazon Prime is the best way to access unlimited entertainment content such as movies, web shows, and TV shows. Visit Amazon.co.uk mytv to activate Amazon prime video. You will need a 6-digit unique activation code to activate Amazon Prime Video. Without activation code, you can't access Amazon account or activate amazon device.
primevideo.com/mytv
amazon.com/mytv
paypal login
paypal login
paypal login
amazon.com/redeem



Unknown said...


The world has enjoyed their Prime membership on larger-screens. www.amazon.com/mytv has made it easy. MyTV App registration is your best option for streaming all of the Amazon Prime shows to your Smart TVs. The above article will solve all your registration, login, verification problems. Now all you have to do is put on your comfy clothes and enjoy the theatre-like experience at home. Log in with your Amazon Prime Login account to access all your favorite web series and original web shows on your smart television.
amazon.com/code
amazon.com/mytv
amazon.com/mytv
amazon.com/redeem
amazon.com/mytv

Unknown said...

Amazon is one the largest multinational companies worldwide that contributes to technological advancements and makes people's lives easier. Amazon is not only the largest online retailer, but it has also been recognized as a leader in multinational technology around the world. Amazon offers a wide range of technological devices including the Echo Dot and Fire TV, as well as Cloud Cam, Kindle, Fire TV, Fire TV, and Fire TV. It also offers entertainment services such as Prime Video, Music Unlimited and Amazon Digital Game Store.
amazon.com/redeem
primevideo/mytv
amazon.com/code
amazon.com/code
www.amazon.com/mytv

faaantas said...

Hey friend, it is very well written article, thank you for the valuable and useful information you provide in this post. Keep up the good work! FYI, please check these depression, stress and anxiety related articles:
the intelligent investor pdf ,

eToro Login said...

As one of the biggest and oldest Bitcoin exchanges worldwide, Coinbase is consistently called one of the very best locations to buy and sell crypto online, thanks to our outstanding service, low charges, versatile funding choices and rigorous security requirements– but this is just part of the story.

Coinbase login |

Unknown said...

www.amazon.com/mytv: Enter the amazon activation code/amazon myTV code shown on your smart TV screen at Amzaon.com/mytv to register your compatible device with Amazon Prime. Enjoy unlimited movies and other web shows.
amazon.com/mytv
amazon code
amazon com code
amazon.com/code
amazon.com/us/code

Unknown said...

Amazon is one the largest multinational companies worldwide that contributes to technological advancements and makes people's lives easier. Amazon is not only the largest online retailer, but it has also been recognized as a leader in multinational technology around the world. Amazon offers a wide range of technological devices including the Echo Dot and Fire TV, as well as Cloud Cam, Kindle, Fire TV, Fire TV, and Fire TV. It also offers entertainment services such as Prime Video, Music Unlimited and Amazon Digital Game Store.
amazon.com/code
lowe's gift card balance
amazon code
target gift card balance
Target gift card balance

Anonymous said...

KuCoin, being one of the largest cryptocurrency exchanges, offers a diverse selection of crypto assets. The kucoin crypto trading website has grown to incorporate almost 200 cryptocurrencies and 400 markets, offering among the most active cryptocurrency exchanges worldwide. Kucoin was founded on morality and principles to provide its users with all of the equipment and skills that contemporary users require, as well as a great customer service that is available 24/7 a day, 7 days per week and through its webpage, messaging ticketing system, and other channels for resolving issues. KuCoin login | coinbase pro login

Unknown said...

All-in-one Canon Inkjet printers are suitable for home, business, school, and others to improve productivity. You can easily set up your Canon printer through drivers from
Canon.com/ijsetup, wireless connection, USB, and a few components.

Once you are done with the driver setup via canon.com/ijsetup , you will have to insert a pile of pages into the printer tray for printing the documents..

Visit ij.start.canon | ij.start canon and find out the best way to download Canon printer drivers.

anand said...

Thanks to this type of article news that may worth it to read.

Cristina Parker said...

The Accessibility for Ontarians with Disabilities Act (AODA) is an accessibility act established in 2005. Under this act, the websites must have certain accessibility features. AODA website services providers scans and audits the websites to identify the key accessibility issues. Then, the accessibility experts suggest changes that are needed to make the website AODA compliant.
VPAT Service Provider
508 compliance for websites

vasavi atlantis said...

Good,Thanks for the useful information

vasavi atlantis is a new under construction project in Narsingi near Gachibowli,Hyderabad.Vasavi Atlantis In Narsingi is built up in 12 acres, 8 towers, 2199 units, 70% open spaces.They offer 2 BHK, 3 BHK, and 4 BHK Residential apartments with world class amenities and high standard specifications. The size andrange of these residential apartments is 1250 SFT to 3200 SFT.This project is constructed very careful manner with latest technologies and modern designs.

John Millar said...

I am lenient and won't give you a tough requirement that I should score a top grade.If there was somewhere to provide feedback on the quality of your work I would be glad to provide one for your Managerial Accounting Assignment Help. Since I have not seen any place then I am just going to write here. I loved how the Calculus Assignment Helplessons were handled. The Myob Assignment Help tutor you assigned me simplified programming for me and made me love it. He was available for daily tuition and never got tired of my never-ending questions and because of that i would love you to assign me a Arcgis Assignment Help who can make meunderstand Tableau Assignment Help even better. I also have two other classmates who need assistance as well. One needs a Amazon Swot And Pestel Analysis because his grades were moving on a downward trend.

ella said...


Amazing website, Love it. Great work done. Nice website. Love it. This is really nice.

FMovies | FMovies

snr the elite said...

Nice Blog, I feel like all your ideas are incredible! Great job!!! Aim also share some information with you about SNR The Elite is developed by SNR Avenue, Located in Gopanpally, Hyderabad. SNR Avenues is India’s speedy developing assets Improvement Company. SNR Avenues attention is at the improvement of top rate residential & business properties, which deal with the necessities of our clientele. It is provides 2 & 3 bhk luxury flats available for sale in Affordable prices. Call +91-7070707098

Essien said...

Its a nice and amazing article and I wish coming around for more powerful update. Thanks for sharing your knowledge. Also visit addendum jupeb admission list for futo (1st Batch)

Roy said...

Thank you for sharing this insightful, and critical information for common people like us, hope your work will boost every visitor’s knowledge just like it did with mine.
Disneyplus.com login/begin | Disneyplus.com/Begin

Unknown said...

ShibaSwap's Smart Contracts. ShibaSwap Architecture. SWAP/DeX and AMM. BURY (Stake) Calculating BURY returns to Woof. Yield Farm/DIG. Woof Architecture. Report a Bug. Powered By GitBook. Calculating BURY returns to Woof.

all login information said...

"This blog is awesome keep posting (please visit my blog Shiitake Fortune Teller
Wellsfargo.com Login
SafuuX"

Sankii said...

Thanks For this information Coinbase Wallet provides the user with a facility using which they can track the performance of their crypto portfolio and improve it in the best possible way.

mbuotidem said...

Thank you for the information it really help student to know their levels check lasu fce abeokuta sandwich degree admission requirements

Henry Ford said...

PikaShow is an Indian-origin Streaming App, primarily workable on Android and iOS devices. The app counts among the top 10 most downloaded Stream Apps on the Play Store due to its unmatched built-in characteristics.
Pikashow Apk -- Download 2023

turnersmith said...

Exodus Web3 Wallet
is a versatile and user-friendly solution designed to empower you in managing, storing, and trading various cryptocurrencies. In this comprehensive guide, we'll walk you through the features, benefits, and steps to get started with Exodus Wallet.

jain said...


Compare Tele Latino APK with other streaming apps. See how it stacks up and why it might be the best choice for you.
Find out which devices are compatible with Tele Latino APK. Ensure your device can run the app smoothly.
Tele Latino Apk
Tele Latino Apk