Fibonacci-tal

Denne bog er en "opskrift" på, hvordan man kan skabe et lille program, der kan danne Fibonacci-talfølger.

C++Rediger

#include <iostream>

using namespace::std;

main()
{
int a=0;
int max=10;
long double b=1, c=1;

while (a<max)
{
if ((a%2)==0){c=b+c;cout << c << ", ";}
if ((a%2)==1){b=b+c;cout << b << ", ";}
a++;  
}

return 0;
}

C++Rediger

#include <iostream>
using namespace std;
int fib(int n);   // funktion til at finde tallet
int main()
{
    int n, resultat;
    cout << "Indsaet et nummer i raekkefoelgen: ";
    cin >> n;    
    resultat = fib(n); // kalder på funktionen fib(n), som regner nummeret ud   
    cout << "Fibonacci's " << n << " nummer i raekkefoelgen er " << resultat << endl;
    return 0;
}
int fib(int n)
{
    if ( n < 3) 
    {
         return (1);
         }
    else 
    {
         return ( fib(n-2) + fib(n-1));
         }
}

PerlRediger

#!/usr/bin/perl

use bigint;

my ($a, $b) = (1, 1);
for (;;) {
    print("$a\n");
    ($a, $b) = ($b, $a+$b);
}

JavaRediger

<script type="text/javascript">
var limit = 30;
y = new Array;
y[0] = 1;
y[1] = 1;

for(var i=1; i<=limit; i++)
{
   y[i+1] = y[i]+y[i-1];
   document.write(y[i] + '<br />');
}
</script>

PHPRediger

<?php
function Fibonacci($num)
{
    $y = array();
    $y[0] = 1;
    $y[1] = 1;

    for($i = 1; $i<=$num; $i++)
    {
        $y[$i+1] = $y[$i-1]+$y[$i];
        echo $y[$i]."<br />";
    }
}

Fibonacci(10);
?>

PHPRediger

<?php
function fibonacci($num){
	if ($num == 0){
		return 1;
	}
	elseif ($num == 1){
		return 1;
	}
	else{
		return fibonacci($num-1) + fibonacci($num-2);
	}
}


$input = $_GET["fib"];
echo Fibonacci($input);
?>

ASPRediger

<%
function Fibonacci(counter)
	Dim n1
	Dim n2
	Dim temp2
	n1 = 1
	n2 = 1
	
	Do while not i>counter
		Response.write n1 &", "
		temp2 = n2
		n2 = n1+n2
		n1 = temp2
		i = i + 1
	loop
End function
Fibonacci(10)
%>

PythonRediger

a, b = 0, 1
while b < 20000:
    print b,
    a, b = b, a+b

Program til udregning af et bestemt nummer i talfølgen

a = 0;
b = 1;
number = 0
at = 0
bt = 0
count = 0

maxcount = int(input("Hvilket nummer vil du tælle til?: "))


while(count < maxcount):
    number = a+b
    
    b = a
    a = number
    count = count + 1
    if(count == maxcount):
        print ("Dit nummer blev: ", number)

ScalaRediger

def f(n : Int) : Int = n match {
    case 0 => 0;
    case 1 => 1;
    case n => f(n - 1) + f(n - 2)
}

F#Rediger

let printFibs amount =
    let rec currentFib a b i =
        if i < amount then
            printfn "%d" a
            currentFib (a + b) a (i + 1)
    currentFib 1L 0L 0