//

# Các Đoạn Code Tính Dãy Fibonacci Dãy Fibonacci là dãy vô hạn các số tự nhiên bắt đầu bằng hai phần tử 0 và 1, các phần tử sau đó được thiết lập theo quy tắc mỗi phần tử luôn bằng tổng hai phần tử trước nó. Đối với chúng ta, các đoạn mã ngôn ngữ C dùng để giải bài toán tính dãy Fibonacci này cũng đã trở nên rất quen thuộc. Dưới đây là một số ví dụ mẫu tính Fibonacci được giải bằng một số các ngôn ngữ khác nhau:

Trong C:

```/**
* You'll notice that we need to include a header file that
* contains functions we need to use. Being a compiled language,
* it's inefficient to include functions that aren't needed.
* stdio.h contains functions for reading from and writing to the console
*/

#include <stdio.h>

/**
* In C, the program executes the main function. You should also take note
* that we must declare a return type for the function. In this case, it's
* an integer, and we return 0 to indicate successful completion of the
* program.
*/

int main ()
{
/* Notice that we need to declare our variables, and their type */

int n;

/* printf prints a formated string to the stdout */

printf("\nHow many numbers of the sequence would you like?\n");

/* scanf reads a formated string from the stdin. We are expecting an integer here. */

scanf("%d",&n);

/* Here we call the fibonacci function */

fibonacci(n);

/* Finally, return 0 */

return 0;
}

/**
* This is the simple fibonacci sequence generator. Notice also, we
* declare the type of variable we expect to be passed to the function.
*/

int fibonacci(int n)
{
/**
* Here we declare and set our variables.
*/
int a = 0;
int b = 1;
int sum;
int i;

/**
* Here is the standard for loop. This will step through, performing the code
* inside the braces until i is equal to n.
*/
for (i=0;i<n;i++)
{
printf("%d\n",a);
sum = a + b;
a = b;
b = sum;
}
return 0;
}
```

Trong PHP:

```<?php
/**
* This is our main function. In PHP, there isn't really a need for this to be
* a function, but to keep consistant, I've placed it there anyway, and called
* it from the script. In keeping with good programming practices, this script
* exits with a status 0. Any other status would indicate an error condition.
*/

function main(){

printf("How many numbers of the sequence would you like?\n");

/*
* To read from stdin in php, you open it as a file handle, and use
* the standard file reading functions
*/

\$fr=fopen("php://stdin","r");
\$n = rtrim(fgets(\$fr,128));
fclose (\$fr);

/* Then we call the fibonacci function */
fibonacci(\$n);
exit(0);
}

/**
* The fibonacci function should look familiar.
*/

function fibonacci(\$n){
/*
* Notice that in PHP, we do not have to declare our variables, nor must we
* declare their types. Also see how variables in PHP are prefaced with the
* dollar sign. Other than that, this is identical to the C version of this function.
*/
\$a = 0;
\$b = 1;
for (\$i = 0; \$i < \$n; \$i++){
printf("%d\n",\$a);
\$sum = \$a+\$b;
\$a = \$b;
\$b = \$sum;
}
}

/**
* In PHP, program execution starts here. It isn't neccessary to place functions
* ahead of the program, but it's a good practice. In a larger application, these
* functions would be in seperate files. Again, since PHP is a procedural language,
* I could have simply included the contents of the main function here, rather than
* defining a function and calling it.
*/

main();

?>```

Trong BASH:

```# Here is our main function. Like PHP, I could have simply placed this in the script
# rather than having a function. You notice that like C and PHP, the printf function
# still exists. Unlike C and PHP function calls do not enclose the parameters with
# paraenthsis.

function main {
printf "\nHow many numbers of the sequence would you like?\n"

# Bash lets us use a function "read" to get input from stdin
# Notice that we are not using a dollar sign in front of the variables when
# we set them, but we need to when we use them.

fibonacci \$n

# Again, I'm exiting with status 0

exit 0
}

# Starting to look familiar? This function is actually a little different than the
# C style for loop that we've used before. Instead we use while..do..done to accomplish
# the same thing. You'll also see that rather than specifying parameters in the
# function;s declaration, we simply reference the variable "\$1" to get the first parameter
# passed when the function was called.

function fibonacci {
a=0
b=1
i=0

while [ \$i -lt \$1 ]
do
printf "%d\n" \$a
let sum=\$a+\$b
let a=\$b
let b=\$sum
let i=\$i+1
done
}

main```

Trong Perl:

```# Functions in Perl are called subroutines. Like bash, you don't define the
# parameters in the function declaration. We'll see how to access the parameters
# when we look at the Fibonacci subroutine below.

sub main {

# Again, the ubiquitous printf function. Apparently a staple of programming
printf "\nHow many numbers of the sequence would you like?\n";

# Once again, we don't need to declare variables before using them.
# Perl's scalar variables, prefaced with \$, can be either strings or numbers
# We use <STDIN> to get the data from stdin here

\$n = <STDIN>;

# As in PHP, we need to remove the newline at the end

chop \$n;

&fibonacci(\$n);

exit 0;
}

# Except for the first line declaring the subroutine, and the different way that
# parameters passed to the subroutine are passed, this is identical to the PHP version

sub fibonacci {
\$a = 0;
\$b = 1;

# So now we see the parameter being used here. For clarity, I have written the for
# loop using \$n like the other examples. To set \$n using the first parameter passed
# to the subroutine, I access the scalar variable \$_, which is the first element
# of the parameter array @_

\$n = \$_;

for (\$i=0;\$i<\$n;\$i++){
printf "%d\n", \$a;
\$sum = \$a + \$b;
\$a = \$b;
\$b = \$sum;
}
}

&main;```

Trong Python:

```# Import the system library. This allows us to access stdin later.
import sys

# Here's our main function. Python is pretty efficient here. You
# should notice that there are no braces. Python is dependant on
# whitespace to define blocks.

def main():
print "\nHow many numbers of the sequence would you like?"
fibonacci(n)

# Here's the fibonacci function. Like in Perl, you can assign multiple
# variables on a line without using a temporary variable. Also, the for
# loop here works more like a foreach loop by setting a range from 0 to n.

def fibonacci(n):
a,b = 0,1
for i in range(0,n):
print a
a,b, = b,a+b

main()```

Trong Ruby:

```# In Ruby, we define a function with def...end functions can accept parameters,
# but don't have to, and you can leave off the parenthesis if your function does
# not need them.

def main
printf "\nHow many numbers of the sequence would you like?\n"

# Here, STDIN is a constant, but like everything in Ruby, it's also a class, so
# we use the readline method to get our input. to_i casts our input to an integer

fibonacci(n)
end

# Here is a good example of something that is cool about Ruby. The times method
# works just like it sounds, it will do something n times. As in Perl and Python,
# we don't need a temp variable here to swap the values for a and b.

def fibonacci(n)
a,b = 0,1
n.times do
printf("%d\n", a)
a,b = b,a+b
end
end

main```

Trong Java:

```/*
* Much like C's stdio.h, the java.io.* classes will let us access stdin and stdout.
*/

import java.io.*;

/*
* Like Ruby, in java, everything is an object. To write a program, you'll need to
* start by declaring a class. As in C, our program execution starts with the main
* function. Also like C, Java is a compiled language, so you'll need to compile
* the code and then run the class using the java interpreter.
*/

class Fibonacci {

/*
* So here we are defining the main function. Remember that this is supposed to
* actually run this program, so the function needs to be `public`, in addition,
* it's `static`, meaning we can call this method without an object of the Fibonacci
* class being instantiated, and it doesn't need to return anything, as it will
* run by the interpreter, which will handle the exit status.
*/

public static void main(String args[]) {

/*
* We are using System.out.println here, but newer versions of Java have the printf method.
*/

System.out.println("How many numbers of the sequence would you like?");

/*
* I'm sure there's more than one way to skin a cat, but to read stdin here, we
* are creating a new BufferedReader, which will read one line of input.
*/

/*
* Now here is a concept we haven't addressed yet. The java compiler complains if
* you try to call a method that could throw an exception (error), so I've included
* an example here of how to handle the exceptions that could be thrown. Also, like
* in our previous examples, we are casting the input to an integer.
*/

try {
int n = Integer.valueOf(input).intValue();
fibonacci(n);
} catch (NumberFormatException e){
System.out.println("That is not an integer. Please enter an integer value");
} catch (IOException e) {
System.out.println("I did not recieve an input");
}
}

/*
* So here is our Fibonacci function. like the main function, it is public and can be
* called without creating a Fibonacci object. We've also introduced a new method of
* calculating the sequence without using a temporary variable. In a later post, I will
* examine the different algorithms used to calculate the Fibonacci sequence, and compare
* performance in multiple languages.
*/

public static void fibonacci(int n){
int a=0,b=1;

for (int i=0;i<n;i++){
System.out.println(a);
a=a+b;
b=a-b;
}
}
}```

~Sưu Tầm~

## Discussion

### 4 thoughts on “Các Đoạn Code Tính Dãy Fibonacci”

1. Nice Information.. Thx for sharing this

Posted by Marie Chelle | 07.10.2010, 22:02
2. Nice code!
Fibonacci in Python is very beutiful!

Posted by giaosudau | 02.01.2011, 11:07
3. c# ??????

Posted by bao | 25.10.2011, 23:53
• Ý bạn là thiếu C# đó hả? 🙂

Posted by Fisama | 12.11.2011, 07:49 Jungle on Sửa Lỗi: java.rmi.UnmarshalExc… gojiactives funciona on Cách Tải Ảnh Vào Và Hiện Thị Ả… sprifi.com on Cách Tải Ảnh Vào Và Hiện Thị Ả… Bell on Cách Tải Ảnh Vào Và Hiện Thị Ả… Nhật Quang on Cách Tải Ảnh Vào Và Hiện Thị Ả… phạm quốc vinh on Tạo Danh Mục Menu Ở Trang Site… Vien Tran on Các công cụ (IDE) thông dụng c… Fisama on Các Đoạn Code Tính Dãy Fi… Fisama on Video Dạy MVC 2.0 Của Microsof… Fisama on Video Dạy MVC 2.0 Của Microsof…