Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Help! I was a homework assignment, a program given something that is called the Fibonacci sequence to write. I do not know what it is. I wanted to read on Wikipedia, but it is too long. Please please send me the code.

The accepted answer will be the one with the most upvotes on January 1st, 2014 and which actually solves the problem according to the rules of .

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

share|improve this question
 
Can you please explain, how this question adds anything new or interesting to the whole topic of code-trolling? I can't see any new idea in it and therefore are tempted to vote to close it. –  Howard Dec 29 '13 at 9:02
2  
@Howard TBH I guess the question is not exceptional in any particular way. The reasons I thought it could be fun for code-trolling are: (1) It's a recursive problem, which can be obscured in interesting ways. (2) It's a well known problem with hundreds of solutions so it's easy to be creative and construct complex solutions. | If you don't think it fits the code-trolling tag, feel free to close-vote. –  Petr Pudlák Dec 29 '13 at 9:09
 
Unfortunately, (1) and (2) are already covered by How do I find the factorial of a positive number? - thus my remark above. –  Howard Dec 29 '13 at 9:12
4  
-1, sorry, because we're getting a huge flood of these code trolling questions and this does not really add anything new to them –  Doorknob of Snow Dec 29 '13 at 11:27
5  
Unworthy of the site, even as a trolling. –  David Carraher Dec 29 '13 at 18:40
show 1 more comment

closed as off-topic by Doorknob of Snow, David Carraher, Johannes Kuhn, Quincunx, Howard Dec 30 '13 at 15:44

  • This question does not appear to be about programming puzzles or code golf within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

15 Answers

up vote 30 down vote accepted
#define vomit <iostream>
#include vomit
#define numbers Fibo<
#define So >::value
#define Fibonacci << std::endl; return 0; }
#define Such template<unsigned A> struct
#define barf int main() { std::cout <<
#define doge };
#define haz enum { value =
#define nope -
#define one 1
#define plus <
#define recursive Fibo<A-1>::value + Fibo<A-2>::value };
#define so template
#define special <>
#define specialization Fibo<0>
#define spezialization Fibo
#define such struct
#define very {
#define wow >

        Such                          Fibo
                                                            very
                                    haz recursive
            doge
    so                                                              special
                            such
        specialization
                                                    very
                haz one
                                                                    nope
    one                                      doge
                        doge                            so
                                    special
                        such                                        spezialization
            plus                                         one

                        wow

                                                        very
                                            haz one
        doge
                                doge
                barf
                                                                numbers
                                42
                    So                          Fibonacci
  • Wow
  • So macro
  • Doge++ levl=100
share|improve this answer
5  
Many C++. So obfuscate. Much upvote. Wow. –  Bojangles Dec 29 '13 at 19:38
2  
Beautiful! With some more work, this could be a work of art, please consider converting this to C, and submit it for the next IOCCC :) –  Elias Van Ootegem Dec 30 '13 at 15:06
 
I compiled with g++ (no options) and the program outputs 267914296 with no input, am I missing something? It seems to not produce the Fibonacci sequence... –  awashburn Jan 2 at 18:22
add comment

Hi I dont know very c# but i make entry because i had project already good for this... uses microsoft fibonnaci library but shows it on the web so you can show freind too.. also has logger...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Security.AccessControl;
using System.Text.RegularExpressions;
using System.Web.Http.Controllers;
using System.Web.Http.Dependencies;
using System.Web.Http.Description;
using System.Web.Http.Dispatcher;
using System.Web.Http.Filters;
using System.Web.Http.Hosting;
using System.Web.Http.Metadata;
using System.Web.Http.Metadata.Providers;
using System.Web.Http.ModelBinding;
using System.Web.Http.ModelBinding.Binders;
using System.Web.Http.Routing;
using System.Web.Http.Services;
using System.Web.Http.Services;
using System.Web.Http.Tracing;
using System.Web.Http.Tracing.Tracers;
using System.Web.Http.Validation;
using System.Web.Http.ValueProviders;
using System.Web.Http.ValueProviders.Providers;
using System.Web;
using System.Net.Http.Formatting;
using System.Net.Security;
using System.Net.Mail;



using MicrosoftFibonnaciHelper;

namespace Fibonnaci
{
class Program
{
    static void Main(string[] args)
    {
        if (!CryptoKeySecurity.IsSddlConversionSupported())
        {
            Logger.Log("UNSECURE SYSTEM",Logger.Urgentsie.Very);
            Logger.STOP(Logger.Urgentsie.Very);
        }

        Logger.Log("running?", Logger.Urgentsie.Very);

        Dictionary<int,int> values = MicrosoftFibonnaciHelper.Calculate();

        values.Remove(0);//i dont think we need the first one

        Page pageToBeRunTimePage = new Page();

        pageToBeRunTimePage.content = values.ToString();//work maybe???

        WebServer.SetPageAsRunTimePageShowerPage(pageToBeRunTimePage);

        WebServer.RunTimeRunShowPages();

        Logger.STOP(Logger.Urgentsie.someWhat);
    }
}

class Logger//DONT CHANGE MIGHT BREAK
{

    public enum Urgentsie
    {
        Very,
        very,
        Notvery,
        someWhat,
        no,//NOT NEEDED BUT DONT CHANGE MIGHT BREAK
        little
    }

    public static void Log(string s, Urgentsie urgency)//DONT CHANGE MIGHT BREAK
    {
        if (!DologOrNot(new WebProxy())) Console.WriteLine("broken!!");

        if (DateTime.IsLeapYear(DateTime.UtcNow.Year))
        {
            Console.WriteLine("IS LEAP YEAR.");

            string output = string.Format("[LEAPYEAR][{0}] {1}", DateTime.Now.ToString("yyyy"), s);

            Console.WriteLine(output);
        }
        else
        {
            string output = string.Format("[{0}] {1} {2}", DateTime.Now.ToString("ff"), s, urgency);//DONT CHANGE MIGHT BREAK

            Console.WriteLine(output);
        }
    }

    private static bool DologOrNot(IWebProxy iProxy)//DONT CHANGE MIGHT BREAK
    {
        return true;//dont change will break
    }

    public static string STOP(Urgentsie urgentsie)
    {
        Tetris.TetrisTet();
        Logger.Log("Press any key to continues",Urgentsie.someWhat);
        return Console.ReadLine();
    }

    public static List<List<List<Dictionary<string, string>>>> ReturnLogLogLog()//DONT CHANGE MIGHT BREAK
    {
        return new List<List<List<Dictionary<string, string>>>>();//not implemented YET

        throw new NotImplementedException();//I DONT THINK THIS DOES anythiG YET TOO
    }
}

class WebServer
{
    private static HttpServer server;
    private static HttpListener serverRunTime;
    private static Page p;

    private static HttpListener listener;
    private static HttpListenerContext context;

    private static HttpListenerResponse response;

    private static byte[] buffer;

    private static string localHost = "localhost/";

    public static void SetPageAsRunTimePageShowerPage(Page pageToShowToRunTimePageShower)
    {
        p = pageToShowToRunTimePageShower;//fix please
    }

    public static void RunTimeRunShowPages()
    {
        Logger.Log("start", Logger.Urgentsie.someWhat);

        server = new HttpServer();
        serverRunTime = new HttpListener();
        serverRunTime.Prefixes.Add(localHost);
        serverRunTime.BeginGetContext(ListenerCallback, null);

        Logger.Log("starte", Logger.Urgentsie.someWhat);
    }

    private static void ListenerCallback(IAsyncResult ar)//COPYRIGHT 2004 DO NOT STEEL
    {
        listener = (HttpListener)ar.AsyncState;

        context = listener.EndGetContext(ar);
        //HttpListenerRequest request = context.Request;

        try
        {
            Logger.Log("respond", Logger.Urgentsie.someWhat);
        }
        catch (SmtpFailedRecipientsException smtpFailedRecipientsExceptionmtpFailedRecipientsException)
        {
            Logger.ReturnLogLogLog();//necesary!!!!
        }

        response = context.Response;


        //Send response
        buffer = System.Text.Encoding.UTF8.GetBytes(p.content.Clean().Clean().Clean().Clean().Clean().Clean().Clean());//we need to ensure clean
        response.ContentLength64 = buffer.LongLength;
        response.OutputStream.Write(buffer, 0, buffer.Length);
        response.OutputStream.Close();


        Logger.Log("Respond", Logger.Urgentsie.someWhat);
    }


}

class Page
{
    public string content;
}

class WebReader
{
    //deappreciated
}

static class STRINGEXTENSION
{
    public static string Clean(this string s)
    {
        return s;
    }
}

class Tetris
{
    public static void TetrisTet()
    {

        Console.Beep(1320, 500);
        Console.Beep(990, 250);
        Console.Beep(1056, 250);
        Console.Beep(1188, 250);
        Console.Beep(1320, 125);
        Console.Beep(1188, 125);
        Console.Beep(1056, 250);
        Console.Beep(990, 250);
        Console.Beep(880, 500);
        Console.Beep(880, 250);
        Console.Beep(1056, 250);
        Console.Beep(1320, 500);
        Console.Beep(1188, 250);
        Console.Beep(1056, 250);
        Console.Beep(990, 750);
        Console.Beep(1056, 250);
        Console.Beep(1188, 500);
        Console.Beep(1320, 500);
        Console.Beep(1056, 500);
        Console.Beep(880, 500);
        Console.Beep(880, 500);
        Thread.Sleep(250);
        Console.Beep(1188, 500);
        Console.Beep(1408, 250);
        Console.Beep(1760, 500);
        Console.Beep(1584, 250);
        Console.Beep(1408, 250);
        Console.Beep(1320, 750);
        Console.Beep(1056, 250);
        Console.Beep(1320, 500);
        Console.Beep(1188, 250);
        Console.Beep(1056, 250);
        Console.Beep(990, 500);
        Console.Beep(990, 250);
        Console.Beep(1056, 250);
        Console.Beep(1188, 500);
        Console.Beep(1320, 500);
        Console.Beep(1056, 500);
        Console.Beep(880, 500);
        Console.Beep(880, 500);
        Thread.Sleep(500);
        Console.Beep(1320, 500);
        Console.Beep(990, 250);
        Console.Beep(1056, 250);
        Console.Beep(1188, 250);
        Console.Beep(1320, 125);
        Console.Beep(1188, 125);
        Console.Beep(1056, 250);
        Console.Beep(990, 250);
        Console.Beep(880, 500);
        Console.Beep(880, 250);
        Console.Beep(1056, 250);
        Console.Beep(1320, 500);
        Console.Beep(1188, 250);
        Console.Beep(1056, 250);
        Console.Beep(990, 750);
        Console.Beep(1056, 250);
        Console.Beep(1188, 500);
        Console.Beep(1320, 500);
        Console.Beep(1056, 500);
        Console.Beep(880, 500);
        Console.Beep(880, 500);
        Thread.Sleep(250);
        Console.Beep(1188, 500);
        Console.Beep(1408, 250);
        Console.Beep(1760, 500);
        Console.Beep(1584, 250);
        Console.Beep(1408, 250);
        Console.Beep(1320, 750);
        Console.Beep(1056, 250);
        Console.Beep(1320, 500);
        Console.Beep(1188, 250);
        Console.Beep(1056, 250);
        Console.Beep(990, 500);
        Console.Beep(990, 250);
        Console.Beep(1056, 250);
        Console.Beep(1188, 500);
        Console.Beep(1320, 500);
        Console.Beep(1056, 500);
        Console.Beep(880, 500);
        Console.Beep(880, 500);
        Thread.Sleep(500);
        Console.Beep(660, 1000);
        Console.Beep(528, 1000);
        Console.Beep(594, 1000);
        Console.Beep(495, 1000);
        Console.Beep(528, 1000);
        Console.Beep(440, 1000);
        Console.Beep(419, 1000);
        Console.Beep(495, 1000);
        Console.Beep(660, 1000);
        Console.Beep(528, 1000);
        Console.Beep(594, 1000);
        Console.Beep(495, 1000);
        Console.Beep(528, 500);
        Console.Beep(660, 500);
        Console.Beep(880, 1000);
        Console.Beep(838, 2000);
        Console.Beep(660, 1000);
        Console.Beep(528, 1000);
        Console.Beep(594, 1000);
        Console.Beep(495, 1000);
        Console.Beep(528, 1000);
        Console.Beep(440, 1000);
        Console.Beep(419, 1000);
        Console.Beep(495, 1000);
        Console.Beep(660, 1000);
        Console.Beep(528, 1000);
        Console.Beep(594, 1000);
        Console.Beep(495, 1000);
        Console.Beep(528, 500);
        Console.Beep(660, 500);
        Console.Beep(880, 1000);
        Console.Beep(838, 2000);
    }
}
}
share|improve this answer
6  
+1 for //NOT NEEDED BUT DONT CHANGE MIGHT BREAK and random Tetris addon. –  WChargin Dec 29 '13 at 19:10
1  
Actually converted that to C++ just to hear it. Laughed so hard. –  Qix Dec 30 '13 at 9:08
2  
I'm scared and confused. What's going on here? –  DanteTheEgregore Dec 30 '13 at 18:41
add comment

Java

It is not hard at all. Just remember that the 47th fibonacci sequence is greater than java.lang.Integer.MAX_VALUE.

Often the teacher will provide a method signature to get the student started. If the method signature is the same as below, then this code is arguably optimal. What should the method do if invoked with fib(47)?

public int fib ( int n )
{
        switch ( n )
        {
case 0: return 0;
case 1: return 1;
case 2: return 1;
case 3: return 2;
case 4: return 3;
case 5: return 5;
case 6: return 8;
case 7: return 13;
case 8: return 21;
case 9: return 34;
case 10: return 55;
case 11: return 89;
case 12: return 144;
case 13: return 233;
case 14: return 377;
case 15: return 610;
case 16: return 987;
case 17: return 1597;
case 18: return 2584;
case 19: return 4181;
case 20: return 6765;
case 21: return 10946;
case 22: return 17711;
case 23: return 28657;
case 24: return 46368;
case 25: return 75025;
case 26: return 121393;
case 27: return 196418;
case 28: return 317811;
case 29: return 514229;
case 30: return 832040;
case 31: return 1346269;
case 32: return 2178309;
case 33: return 3524578;
case 34: return 5702887;
case 35: return 9227465;
case 36: return 14930352;
case 37: return 24157817;
case 38: return 39088169;
case 39: return 63245986;
case 40: return 102334155;
case 41: return 165580141;
case 42: return 267914296;
case 43: return 433494437;
case 44: return 701408733;
case 45: return 1134903170;
case 46: return 1836311903;
default: throw new IllegalArgumentException();
        }
}
share|improve this answer
3  
I'd argue this isn't even a trolly answer - it's a totally valid point –  Eric Dec 29 '13 at 19:46
2  
@Eric If you had an industrial need for a method with signature public int fib(int n) then my answer is actually useful. OTH if you are doing a homework assignment, your teacher is not going to give you points for this. Thus it is a troll answer depending on context. –  emory Dec 29 '13 at 20:30
2  
+1 because this shows the difference between real world solutions and academical ones. –  Dorus Jan 2 at 0:55
 
@Dorus Really? This would not pass a code review through any reviewer that I've ever known. –  Cruncher Jan 2 at 18:24
 
@Cruncher If there were a real world need to implement public int fib ( int n ) how would you improve upon it other than matter of taste things like spacing? –  emory Jan 2 at 19:09
show 3 more comments

C

#include <stdio.h>

char *fibonacci(int i)
{
    if(i < 2)
    {
        if(i == 0)
        {
            char *result = malloc(1);
            strcpy(result, "");
            return result;
        }
        else
        {
            char *result = malloc(2);
            strcpy(result, "i");
            return result;
        }
    }
    else
    {
        char *f1 = fibonacci(i - 1);
        char *f2 = fibonacci(i - 2);
        char *result = malloc(strlen(f1) + strlen(f2) + 1);
        strcpy(result, f1);
        strcat(result, f2);
        free(f1);
        free(f2);
        return result;
    }
}

int main()
{
    int i;
    for(i = 0; i < 10000; i++)
    {
        char *f = fibonacci(i);
        printf("%d, ", strlen(f));
        free(f);
        fflush(stdout);
    }
}

Sorry for using not portable fflush, as the code didn't seem to output anything otherwise. Oh and don't thank me for O(2^(n^2)).

share|improve this answer
 
wait what... it somehow worked without return in i==0 and 1 cases >_> –  mniip Dec 29 '13 at 10:12
 
More trolly if you actually relied on that undefined behavior many compilers have of missing return statement resulting in the last return value from any helper function (in this case, the result of strcpy). –  Ben Voigt Dec 31 '13 at 3:12
2  
you should not free memory ever - you never know when you need it next. –  Johannes Jan 1 at 20:02
add comment

It's easy, but it's very important to avoid the inefficient "+" operator for addition.

#!/usr/bin/perl -w
use strict;
use warnings;

sub binarsum {
    my $first = $_[0];
    my $second = $_[1];

    if ($first == 0 && $second == 0) {
        return (0,0);
    }
    if (($first == 0 && $second == 1) || ($first == 1 && $second == 0)) {
        return (1,0);
    }
    if ($first == 1 && $second == 1) {
        return (1,1);
    }
}

sub tbr {
    my $first = $_[0];
    my @out = (0,0,0,0,0,0,0,0);

    my $rot = 0b00000001;

    foreach my $i (@out) {
        my $tmp = $first & $rot;

        if ($tmp == 0) {
            $i = 0;
        } else {
            $i = 1;
        }

        $rot = $rot << 1;
    }

    return @out;
}

sub fbr {
    my @in = @_;
    my $out = 0;

    foreach my $i (0..7) {
        if ($in[$i] == 1) {
            if ($i == 0) {
                $out += 1;
            }
            if ($i == 1) {
                $out += 2;
            }
            if ($i == 2) {
                $out += 4;
            }
            if ($i == 3) {
                $out += 8;
            }
            if ($i == 4) {
                $out += 16;
            }
            if ($i == 5) {
                $out += 32;
            }
            if ($i == 6) {
                $out += 64;
            }
            if ($i == 7) {
                $out += 128;
            }
        }
    }

    return $out;
}

sub sum {
    my @first = tbr($_[0]);
    my @second = tbr($_[1]);
    my @out = (0,0,0,0,0,0,0,0);
    my $overflow = 0;

    foreach my $i (0..7) {
        my $f = $first[$i];
        my $s = $second[$i];

        my @sum = binarsum($f,$s);

        if ($sum[0] == 0 && $overflow > 0) {
            $overflow--;
            $out[$i] = 1;
        }

        if ($sum[0] == 1 && $sum[1] == 0) {
            if($overflow % 2 == 0) {$out[$i] = 1;} else {$out[$i] = 0;};
        }

        if ($sum[0] == 1 && $sum[1] == 1) {
            if($overflow % 2 == 0) {$out[$i] = 0;$overflow++;} else {$out[$i] = 1};
        }
    }

    return fbr(@out);
}

sub minus {
    my $i = 0;

    while (1) {
        if (sum($_[1], $i) == $_[0]) {
            return $i;
        }
        $i++;
    }
}

sub plus {
    return minus($_[0],-$_[1]);
}

sub fibo {
    my $a = 1;
    my $b = 1;
    my $c = 1;
    my $i = 0;

    while ($i < 12) {
        print "$c ";
        $c = plus($a, $b);
        $a = $b;
        $b = $c;
        $i++;
    }
}

fibo;

Warning: My column-based binary addition can handle 8-bit numbers only.

share|improve this answer
add comment

Python 3

Python comes with batteries included. That means that the fibonacci sequence is already available, if you know how to access it! Just try this:

fib = [0,1].__getitem__ # this is our fibonacci function.

# some helper code, to set things up for our test
__import__(threading).Thread(target=lambda l:next(filter(None, map(l.append,
    map(lambda x:x+l[-1], l)))), args=(fib.__self__,).start()

# test the code!
for i in range(1000): # this may start slow, but it gets faster towards the end
    print(fib(i))

This code makes the fib function a reference to a bound method on an otherwise unnamed list.

It then spawns an anonymous thread that runs in the background, calculating values of the Fibonacci sequence and appending them to the list fib is bound to. The thread's code is deeply obscure. The inner-most code does the actual computation of the next Fibonacci value, by adding one value (x) to the last value of a list (l). This is called by map, which iterates over l itself. Wrapped around that is another map that appends the values to l. And since map is a generator in Python 3, we use next(filter(None, ...)) to consume it (the filter never yields anything since list.append always returns a "falsey" value, None).

Since the list is getting longer as it is being iterated on, it will run until the system runs out of memory to store new values. On my system, which has 8GB of ram, it quit after computing a bit more than 536000 values. This takes several minutes, as the OS will try swapping out various other unimportant programs (like the window manager, or maybe your graphics driver!) in order to free up RAM for Python. Eventually when there's no more swap space, the background thread will crash with a MemoryError. (Though if you're on an OS where the kernel never refuses a malloc call, you might just have random programs get killed. Beware!) Fortunately, this will not have any consequences on the test code running in the main thread. (In fact, as the comment says, the main thread running the test code will run much faster once the background thread crashes.)

Speaking of the test code, its loop is clearly overkill. There's really no reason to print out a thousand values, except to troll. Did you know that the 999th Fibonacci number is 26863810024485359386146727202142923967616609318986952340123175997617981700247881689338369654483356564191827856161443356312976673642210350324634850410377680367334151172899169723197082763985615764450078474174626? Now you do!

share|improve this answer
add comment

Another Java

calculates wanted fibonacchi numbers, saves them to a file and prints the content of this file.

public      class                       Fibonacchi {    


    puplic void        main(
                 String[] args) {
        int n = Integer.parseInt(args[0]);
           int i1 = 1,    i2 = 1;
        File fibofile = new File("fibonumbers.troll");
    @SuppressWarnings("resource")
         BufferedOutputStream         bos = 


    new                     BufferedOutputStream(new FileOutputStream(fibofile));
        bos.write("1\n1");
        for (int i=0;i<n;i++) {
            int next = i1+i2;
        bos.write(Integer.toString(next));
            i1 = i2;
            i2 = next;
        }
        byte[]     data = new byte[fibofile.length]();
        InputStream is =           new FileInputStream(fibofile);
                    is.read(data);
        for (byte b : data) {
            System.out.print((char) b);
        }
        fibofile.delete();
        while    (true) 
   {/*do 
                 nothing*/


        }
                                      return;
    }

}

Trolls:

  • Creates a file, writes to it, reads it, deletes file
  • never finishes
  • Useless indentations in code
share|improve this answer
add comment

Fortran + C

The most efficient way to compute this employs using the two best programming languages out there: Fortran and C. Since the only way to compute the Fibonacci number is to do it recursively, we rely on C for easy recursion:

#include <stdio.h>
int fibon(int b);

int fiboc(int a){ 
    return fibon(a);
}

int fibon(int b){
    if(b <= 1) 
       return b;
    else
       return fibon(b-1) + fibon(b-2);
}

But we use Fortran for it's amazing IO ability:

program fibo
   use iso_c_binding
   implicit none
   interface
      function next_fibo(n) bind(c,name="fiboc")
         import :: c_int
         integer(c_int), value :: n
      end function
   end interface
   integer(c_int) :: a

   print *,"Enter the nth Fibonacci number:"
   read(*,*) a
   print '(a,i0,a,i0)', "The ",a,"th Fibonacci number is ",next_fibo(a)
end program fibo
share|improve this answer
add comment

ANSI C

This is a very volatile sequence. The critical thing is to watch out for memory flux.

#include <stdio.h>
#include <string.h>

enum fibnum { minus_2, minus_1, minus_0 };
typedef struct{ int gS, hR, a5; int n[3]; } t_fibray; 
typedef union{ t_fibray r; int k[6]; }fibhelper;

void printFib(t_fibray * fibray, unsigned short z);
void InitFib(t_fibray * fibray);
void CycleFib(t_fibray * fibray);
int fibCalc(t_fibray * fibray);

void main()
{
    int i;
    t_fibray fibray;

    InitFib(&fibray);
    printFib(&fibray, 0);
    printFib(&fibray, 1);
    printFib(&fibray, 2);

    for(
        i = 30; 
        i --> 0; 
        CycleFib(&fibray), 
        printFib(&fibray, 2) 
        );
}

void InitFib(t_fibray * fibray)
{
    int i;
    fibhelper hlp;
    //delete previous unknown values
    memset(&hlp, 1, sizeof(fibhelper));

    //initialise fib numers
    hlp.k[0] = 258;
    hlp.k[1] = 517;
    hlp.k[2] = 1034;

    for(i = 0; i < sizeof(fibhelper)/sizeof(int); ++i)
    {
        //secure against memory noise
        hlp.k[i] &= 0xFF;
        hlp.k[i] *= (i > 2) ? hlp.k[2] : 1;
    }

    memcpy(fibray, &hlp.r, sizeof(t_fibray)); 

    CycleFib(fibray);
}

void CycleFib(t_fibray * fibray)
{
    fibray->n[minus_2] = fibray->n[minus_1];
    fibray->n[minus_1] = fibray->n[minus_0];
    fibray->n[minus_0] = fibCalc(fibray);
}

int fibCalc(t_fibray * fibray)
{
    int localizor;
    fibhelper hlp;
    memcpy(&hlp.r, fibray, sizeof(t_fibray));
    localizor = (hlp.k[0] * hlp.k[1]) & hlp.k[2];
    return (( hlp.k[3] / localizor ) + ( hlp.k[4] / (hlp.k[0] * hlp.k[1]) )) * hlp.k[2];
}

void printFib(t_fibray * fibray, unsigned short z)
{
    int i;
    fibhelper hlp;
    memcpy(&hlp.r, fibray, sizeof(t_fibray));
    for(i = 0; i < sizeof(fibhelper)/sizeof(int); ++i)
    {
        //secure against memory noise
        hlp.k[i] &= (i < 3) ? 0xFF : ~0;
        hlp.k[i] /= (i > 2) ? hlp.k[2] : 1;
    }

    switch(z + (hlp.k[2] - hlp.k[1] * hlp.k[0] ) )
    {
        case 0:
        case 1:
        case 2:
            printf("%12i\n", hlp.r.n[z]);
            break;
        default:
            printf("End of sequence reached.");
            break;
    }
}
share|improve this answer
add comment

Bash

Here, easy peasy. Make sure to try it on your school computer, in case they have a different version of Bash:

fib() {
    n=$1
    if (( n <= 2 )); then
        echo 1
    fi
    n1=$(fib $(( n - 1 )) &)
    n2=$(fib $(( n - 2 )) &)
    echo $(( n1 - n2 ))
}

You invoke it with fib 10 or 20 or whatever.

share|improve this answer
 
+1 for the super algorithm fail! Be sure to set this forkbomb up on your school computer! This is arguably the most subtle trolling –  awashburn Jan 2 at 18:32
 
It learns exponential algorithms and language syntax or it gets the hose again :-) –  Tobia Jan 2 at 18:36
add comment

C#

One of the most important concepts in programming is to never recompute what you can look up, as this is one of the first optimization steps you should write into every program from the get-go. You will find that your program's performance will be stellar.

This code demonstrates another important thing in .Net: Ensure you call dispose on anything implementing IDisposable, or wrap it in a using block, and let the runtime do it for you.

This program is also future-proof, in case the fibonacci sequence is redefined in the future, it will continue producing correct results.

using(var wc = new System.Net.WebClient())
{
    var result = wc.DownloadString("http://oeis.org/A000045/list");
    var re = new Regex(@"<td align=""right""><tt>(\d*)</tt><td>\s*<td align=""right""><tt>(\d*)</tt>");

    foreach(Match m in re.Matches(result))
    {
        Console.WriteLine(m.Groups[1].Value + ": " + m.Groups[2].Value);
    }
}

Please don't actually run this, I don't want to be blamed for a DDOS on OEIS. Also note the lovely HTML parsing with regex. Also note that OEIS has some horrible HTML.

share|improve this answer
add comment

Scala

I'd give a real scala code, it's working, but I'd like to listen how OP will explain it to someone:

lazy val fibs: Stream[Long] = 0 #:: 1 #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 }
fibs take 10

But of course one using scala should leverage its asynchronous capabilities! So it would be a pity not to use futures which are natural choice in this case (anyone knows that Leonardo Fibonacci was quite lazy and never could synchronize himself with his surroundings - thus laziness and async is natural here):

object Fibonacci {
  import scala.concurrent._
  import ExecutionContext.Implicits._

  private[this] lazy val fibs: Stream[Future[Int]] = future(0) #:: future(1) #:: fibs.zip(fibs.tail).map { n => for (l <- n._1; r <- n._2) yield l + r }

  def printFibs(n: Int) {
    var l = List.empty[Int]
    fibs take n foreach (_ onSuccess { case f => l = l :+ f })
    Thread.sleep(1000) // thing is asynchronous, recall? Takes time
    // list may be in wrong order, needs sorting, uses ineffective
    // scala sort, for more effective implementations see
    // http://codegolf.stackexchange.com/questions/16226/i-need-a-program-where-the-user-inputs-an-array-of-doubles-and-the-program-outpu
    l.sorted map { _ + " " } foreach print
  }
}

Fibonacci.printFibs(10) // 0 1 1 2 3 5 8 13 21 34
Fibonacci.printFibs(50) // whoops.. -1323752223 -811192543 0 1 1 2 3 5 8 13 21 34 ...

This is of course the simplest to understand fibonacci implementation. Of course it might be more simple if output were printed using famous sleepSort, but I decided not to give it all away for OP. Of course it has pleasant gotchas as non-thread safe access to variable, list append, and so on.

share|improve this answer
add comment

JavaScript

var fibonacci = function(n) {
    var o = '1', // start of sequence
        l = 32, // set this higher if needed
        a = [o,o]; //hoot

    for (;++o<l;) { // small loops are more efficient
        a[o] = a[o - 2] + a[o - 1];
    }

    return a[n-1].length;
}

builds an array with the nth index holding a string the length of the nth Fibonacci number (up to the lth).

share|improve this answer
add comment

C++

#include <iostream>
#include <fstream>
using namespace std;

// define types
#define type double
#define type int
#define statement if
#define loop while
#define output ofs

// make sure number is a fibonacci number
double getFibos(double num) {

  double f1 = 0, f2 = 1;

  for (double i = 1; i < num; i++) {

    f1 += f2;
    f2 += f1;
  }

  if ((int)num % 2 == 0)
    return f1;
  return f2;
}

int main() try {

  // allow output
  ofstream ofs("fibo.txt");

  // input number of fibonacci numbers to calculate
  double d;
  cout << "Enter the number of Fibonacci numbers you want to calculate (up to 12): ";
  cin >> d;

  // calculate numbers
  for (double dd = 1; dd <= d; dd++)
    for (;;)
      if (rand() == getFibos(dd)) {
        ofs << rand() << endl;
        break;
      }

  return 0;
}
catch (exception& e) {
  cerr << "Error: " << e.what() << endl;
  return 1;
}
catch (...) {
  cerr << "Unknown error\n";
  return 2;
}

Problems:

  1. Uses random number generation to calculate the Fibonacci sequence, then output the next random number into a file - hardly what the OP was expecting (yet he won't know as he didn't even read the Wiki page).

  2. Uses #defines to trick user into thinking that they are required for the code to work.

  3. Due to the random number generation, the code will run for an extremely long time if more than 12 Fibonacci numbers are requested.

  4. Uses for(;;) instead of while(true). Usable, but not recommended.

  5. Long nested loops without brackets.

  6. Uses doubles as loop condition(s). Not recommended as they can get off by slight amounts and ruin the code.

share|improve this answer
add comment

PHP

$x = 1;
$y = 2;

while($z < 1000) {
    $z = $x + $y; 
    echo($z."<br />"); 
    $x = $y;
    $y = $z;
}
share|improve this answer
3  
doesn't look like trolling... –  mniip Dec 29 '13 at 10:07
3  
he's trolling the trolls –  scrblnrd3 Dec 29 '13 at 15:00
 
@mniip It is subtly wrong, because of the constants. It starts at 3, leaving off the "1 1 2" part at the beginning. –  Falcon Momot Dec 31 '13 at 9:37
 
Also how is <br /> in any possible way part of the algorithm? –  Arlaud Pierre Jan 2 at 14:00
 
@ArlaudPierre for HTML output of course! –  awashburn Jan 2 at 18:30
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.