tags:

views:

578

answers:

8

This is the expected output:

alt text

We are to make a C program that calculates for the Fabonacci Sequence. We're only allowed up to 3 variables and we're NOT allowed to use loops. And I don't know what to do and how to start.

I hope you guys can help me. :/

+7  A: 

Use recursion:

alt text


Version in C/C++ language:

int fib(int a)
{
    if (a == 0) return 0;
    if (a == 1) return 1;
    return fib(a - 1) + fib(a - 2);
}

Apply suggestion from this answer comments:

Version in C language:

/*
 * -1 is a error handler
 */
int fib(int a)
{
    if (a < 0 || a > 47) return -1;
    if (a == 0) return 0;
    if (a == 1) return 1;
    return fib(a - 1) + fib(a - 2);
}

Version in C++ language:

int fib(int a)
{
    if (a < 0) throw new std::out_of_range("Fibonacci is not defined for negative sign values.");
    if (a > 47) throw new std::overflow_error("Fibonacci for this value was overflow the integer.");
    if (a == 0) return 0;
    if (a == 1) return 1;
    return fib(a - 1) + fib(a - 2);
}
Svisstack
-1 For posting code in response to homework question
qrdl
is there a badge for homework spoilers?
Marco Mariani
Take a deeper look at this code ;-)
tur1ng
We haven't discussed that yet. So I think I'm not allowed to do that. Are there other ways? Isn't it possible if I just use the basic operators or something like that?
rob2k8
@rob2k8: 2 most popular version of this algorihtm is iteratio or recursion. You can search other (eg. parallel) methods but recursion with buffer or something else. But this is a simplest from all of them.
Svisstack
no loop and no recursion? Then what can we use?
yehnan
You're not allowed to use a method that hasn't been discussed yet? What kind of class is this that disallows independent learning? Reminds me of my second grade math teacher who tried to tell me that you can't have decimals in a fraction.
David
use the goto, rob
Marco Mariani
no loop and no recursion ? Make a lookup table.
nos
@David you're right partly; but restricting what one can use of a language is a way to learn too, to make people think more. So it is useful after all.
ShinTakezou
+1 because of reasonless downvoting (spoiling homework is not a good reason for downvoting, expecially when others did too, and gets not downvoted)
ShinTakezou
+1 and you should really rollback the code... Since when giving a correct answer is a reason to downvote?
nico
+1 Correct answer
DRL
Of course I understand what you mean, but what does "dla" stand for? Usually one writes "if"...
Andreas Rejbrand
@qrdl , @Marco Mariani: Same users who creates this topic ask a smillar question few days ago and accepted answer is code solution with 5 upvotes and 0 downvotes. I don't know why my source is not a valid then other homework answers? http://stackoverflow.com/questions/3126696/c-programming-breaking-down-of-money
Svisstack
@Svisstack `function` should be `int` likely, if it is not C-like pseudocode
ShinTakezou
Let's be honest, the code is not quite correct, is it? Have you tried `fib(-1)`?
JeremyP
__to the downvoters to this answer, and upvoters of qrdl comment__ : do you really think that "spoiling" is not a) teaching b) harmless? In fact, the solution can be easily found in the net (even on other Q/A sites), he don't need SO at all. On the other hand, "spoiling" means he gave the right answer, and how a right answer can be considered unuseful? You are just stating your opinion about what teaching should be. And this is off-topic with respect to SO and its voting system, and future users that will read the answer.
ShinTakezou
@JeremyP hmmm, have you tried $F_{-1}$ ? It's a limit of the definition...
ShinTakezou
I agree with ShinTakezou maybe if this had been a more complicated question then giving the answer may not have been acceptable but because he could have easily Googled and found that answer(and probably should have) its acceptable to give the answer.
Gage
@Marco Mariani: Agreed.
Chris
@ShinTakezou You must be new here. It is considered bad to post code in response to homework question, hence the downvote from me and others. Student won't learn from blindly copying code from SO to homework, so the point is to give a clue and let the student to find the answer. Learn the local ethics before teaching others how to behave. When in Rome do like Romans do.
qrdl
@qrdl I find it silly.The solution is already over there.Homework questions are as other Qs.The OP asks for help,people give it as _they_ think it is better;pedagogical opinions are opinions;it could be annoying to see that the OP has not done the smallest effort;but it is a OP problem(or your wasting-time problem),not to be charged on someone-else's Answer.If students are smart,they learn also by analysing an already given solution,not only by "suggestions";and it is strongly true in this case:clue is "recursion",then he searchs "fibonacci recursion" and finds a solution elsewhere,so what?>>
ShinTakezou
Students that don't want to learn won't learn.Others,as said,can learn also analysing a "ready"solution(and in this very case,trying to hide it, is simply silly),and it is how so often learning works (how many "ready solutions" are already into study books?).From SO Q/A mechanism PoV,a homework-spoiling answer can't be an "unuseful" A,being correct and so surely useful for the OP and future readers;unless you are stating that your pedagogical opinions are superior and so the A is "unuseful" not because it is really unuseful(in fact __it is useful__),>>>
ShinTakezou
but since you think that answering correctly to an homework Q is wrong,and who does, must be punished. It is not a matter of being new or old, and people should learn not to comply to "local ethics", expecially when it is indeed a subjective "group" "ethics";you "have heard" it is so, so it must so,and you teach it must be so and the others have to comply? I don't see "local ethics", and if it is somewhere, it is just the opinion of many(but many people having the same opinion does not make the opinion something different from an opinion anyway).>>
ShinTakezou
What is __not an opinion__, it is that the answer __is correct__ and future readers will be able to benefit from it, regardless your personal (and according to you, right and globally shared)pedagogical view.There are not such laws in SO about homework,it's your and your followers perception.Of course,you can have that opinion,and avoid writing the kind of answer the violate your own rules.What I see stupid(more, but not less), is to punish someone to have not your same opinion, and it is what you and your "followers" are doing with a __correct__ answer.>>
ShinTakezou
(And BTW, your adage is totally inappropriate, and moreover it is the kind of adage I label as dangerous, since it states that individuals have to comply despite their own "ethics"; Romans kill bums? then when in Rome you have to kill bums; Romans have sex with not-in-age boys/girls? then you can have sex with not-in-age boys/girls, and so on).
ShinTakezou
Just to note, this algorithm has terrible, I believe exponential, time requirements. Don't use it for real work. Either use a more efficient general solution, or a look-up table.
David Thornley
@qrdl [this reading is for you and your followers](http://meta.stackoverflow.com/questions/10811/homework-on-stackoverflow), in particular I liked this sentence «Don't downvote others who answer homework questions in good faith, even if they break these guidelines» -- I am not here since years, but already learned how to check if what you call "local ethics" is indeed an invention or not.
ShinTakezou
@qrdl another perl, an opinion like yours, but different from yours and the one of your followers: «There should be no distinction between homework and regular questions. SO community members should answer homework questions as completely and definitively as possible.» So where's your local ethics that you know since you are an old user while I "must be new" here?
ShinTakezou
judging by the number of votes of qrdl comment, there is an implied don't ask don't tell army-like policy in stackoverflow.
Robert William Hanks
@ShinTakezou When you finish talking to yourself, read my comment again. I never told that such answers shouldn't be answered - I told that you need to give a clue, point to the right direction, not to give the code. I'm out. You can keep talking to yourself.
qrdl
Well, whatever. Let's be honest. Ethically, you should not simply provide an answer to such a basic, common, CS homework. With these kinds of question I usually limit it to hints or something similar.
BobbyShaftoe
@JeremyP: yyy.. fibonacci don't exist in (-1) point.
Svisstack
@Svisstack: No it doesn't, so why do you allow -1 as input to your function? Especially considering that -1 as input will probably cause a stack overflow.
JeremyP
@Svisstack: btw I did not down vote your answer.
JeremyP
@qrdl I write to myself if no-one reads.And reread (or read) my "alone" speech:I understood that you _allow_ (thx!)answers to this kind of question.I am challenging how silly and _violent_ is imposing,by downvoting+comment,your pedagogical view.Your are saying the Q can be answered,but it is good only if it respects your imagined "local ethics". Homework Q are like any other Q.The guy helped posting the code,__not a wrong answer__,and the A is __for sure useful__ to OP and future readers.There are no reasonable basis for downvoting.Why then doing so?Noone asks you to upvote it anyway!
ShinTakezou
@BobbyShaftoe it is the opposite:since the problem is basic and common and so widely known on the net, there's no harm in providing a full answer, even if you think doing so in general is pedagogically wrong. And I say, it is not pedagogically wrong. I have been a teacher someway; I don't bother where my students get the answer, I pretend they can explain it to me, and answer a pair of question just to be sure they get it. It is up to the student to learn. As I've already said, students that do not want to learn, won't learn. The others,will learn even from a ready given solution as this.
ShinTakezou
@ShinTakezou, well honestly that's just stupid. It is pedagogically wrong. How is it in any way helpful pedagogically speaking? Sure, it is available on the 'Net, but we can't control that. We can only control how we answer questions. Is it fair to the student that spent a few hours trying to figure out the problem without cheating to give the one that cheated the answer so easily? I think something more akin to the Socratic method would be a better fit pedagogically.The simple fact that the answer is a Google away is no justification.Paying someone to do your project is easy too.Is that fine?
BobbyShaftoe
@BobbyShaftoe students that don't want to learn, won't learn (written for the 3rd time).It is not pedagogically wrong. It is just a different pedagogical approach.An incredible amount of knowledge you have comes from having studied an already given "solution".Moreover,since what is ok and what is not for the mind of the OP is not our business after all,so you have no reason to "punish" anybody for having a different pedagogical view.If you have to blame someone,blame directly the OP,write your telling-off about the fact that s/he won't learn if he copies solutions and so on.
ShinTakezou
and of course you are free to answer differently following you beliefs, and I will defend your right to write an answer without a solution against any person downvoting your answer with a comment like "-1 since it does not solve the OP problem".
ShinTakezou
+1 for the clear and concise answer
Andomar
@JeremyP: ok i know the if you run this function with -1, you get unexepted result and this is a right choice, because this is a function to calculate fibonacci value and fibonacci exists only from <0; +infinity) and dont exists in negative sign values, then if you try calculate fibonacci for this values you can get unexcepted result. I can't write if (a < 0) return 0; because for negative sign values fibonacci is not 0 this dont exists, then i cant write if (a < 0) return 1; too.. because 1 is not == not exists.
Svisstack
@Svisstack: You probably don't get "unexpected result" you probably get stack overflow and program crash. You could easily fix the solution by either returning -1 = error for negative integers or by using unsigned ints instead.
JeremyP
@JeremyP unsigned int would make it touch the recursion limit anyway, likely, with values like -1, -2.... The better thing is just a "guard" condition, e.g. `if (n <= 0) return 0;`
ShinTakezou
@Shin Takezou: You are correct but I still think that if the domain of a function is non negative integers, you should use a type that reflects the domain. Of course, since (for 32 bit signed integers) values of n > 47 will cause the answer to overflow you should add a guard condition for that (and the error value should not be 0 because that is the same as one of the legitimate values in the sequence).
JeremyP
@JeremyP I had bugs for this once...If you use uint and the user call the function with -1 (ignoring warnings by the comp,if any),u have no way to catch the error,since -1 becomes 4294967295,which can be a valid input in general;in this case the func is not able to calc it,so on 32bit machines we could add an upper limit.If we use signed int,we can catch the user calling the func with a wrong arg.E.g. in this specific case we could `fprintf(stderr,"fibo seq is not defined for negative numbers")`; and `fprintf(stderr,"it will overflow")` for, say, n>47;they are different kind of error
ShinTakezou
@ShinTakezou , @JeremyP: bugfixed
Svisstack
I actually downvoted for throwing a string instead of a std::exception.
DeadMG
@DeadMG you could have just commented to trigger the fix and make the answer and its code better. - @Svisstack I would give another +1 for being back and try to make it more useful despite all those noises about how homework question should be answered to be a good guy.
ShinTakezou
+5  A: 

I would suspect that if you can't use loops that your professor/teacher intended you to use recursion. Otherwise it's simply a matter of looking up the proper formula, which makes no sense in a programming class.

If recursion is allowed I highly recomend reading this tutorial (assuming you aren't familiar with it).

CheesePls
+3  A: 

http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html

which you can copy here

http://cboard.cprogramming.com/cplusplus-programming/108426-binets-formula.html

long double f(short N) {
    double phi = (1+pow(5,0.5))/2;
    return ceil((pow(phi,N) - pow(1-phi,N))/pow(5,0.5));
}

of course, it's just math, but it does calculate fib(N) without recursion and loops.. you still need a way to print all the values for fib(1)..fib(n) though

what your teacher wants is probably recursion.

Marco Mariani
this solution stop working from small numbers of fibonacci because floting point variables dont have good precision. And this solution is MPC solution of solve normal recursion.
Svisstack
integers don't have arbitrary precision either, at least in C. i just wanted to point out that the function does not require an iteration-recursion /per se/
Marco Mariani
@Svisstack -- this is no problem -- just write a 256 bit (or so) floating point library and you are good to go.
Hogan
let's use GMP then, instead of rewriting it from scratch!
ShinTakezou
@Hogan: on 32/64 bit processor this library would be very slow ;-) i think you dont cary about it, and if you dont cary you can use iteral version of fibonacci without insurance of some algorithm breakdown by the floting point precision (256-bit floating point oprations have precision too;-))
Svisstack
@Svisstack : Why would it be slow? Besides, it is almost sure to be faster than any kind of loop or recursion. Of course it depends on your pow() function and your ceil() function, but as written this is O(1) whereas the best you can do with a loop or recursion is O(N).
Hogan
@Hogan: but pow() and ceil() you must rewrite in 256bit and at this point your solution is not good because must have too cooding to get solution of from any point in x get error results (from a floating point precision) and ceil() pow() in 256bit may be VERY slow
Svisstack
+5  A: 

If loops and recursion are not allowed, pick up fibonacci sequence definition and do it by hand... it is ridicolously boring and uninteresting but it is the most straightforward solution in those restrictions.

a = 0; // 0
b = 1; // 1
a = a + b; // 1
b = a + b; // 2
a = a + b; // 3
b = a + b; // 5

and so on: b holds the n-th and a the (n-1)-th number. (Copy-paste a = a+b; b = a+b; how many times you need...) Copy-pasting fragments of code is allowed?

... (edit) ...

Of course this answer just shows how ridicolous stuffs can get if we put too much rescrictions. If you don't know recursion, you have to learn it, definitively. Or stick into fine mathematics (as other answer shows), but recursion is a powerful tool programmers should know anyway, and the recursive approach is more intuitive than using mathemathical "tricks".

ShinTakezou
LAME...and we probably don't want to give rob2k8 even an inkling of an idea that this sort if thing is even REMOTELY acceptable.
CheesePls
Yeah, it is not... it is just the extreme consequence of prohibiting loops and recursions (since he doesn't know it; so the answer show clearly how silly would it be without even recursion!). The answer is ironically hilarious, and I am sorry to have been forced to write it explicitly; I thought that my final "Copy-pasting fragments of code is allowed?" would have been enough to understand that the answer must not be taken seriously, as you (and your comment upvoter) did.
ShinTakezou
... added details, just in case the OP could become confused and think that the solution is acceptable.
ShinTakezou
+1  A: 

Since loop and recursion aren't allowed,

int fib(int n) {
   int fk1 = 0, fk0 = 1;
main_sub3:
   fk1 += fk0;
   fk0 = fk1 - fk0;
   if (n > 0) {
     -- n;
     goto main_sub3;

*raptor*

KennyTM
Isn't that a loop?
izb
+1 For the Raptors :P
Ivo Wetzel
ewwww goto. But, there are raptors.
CheesePls
for, while, do-while, whatever... are just not-primitive looping mechanisms. A `goto` is the "base" of every loop mechanism (o well, not of all indeed and in a broad sense _recursion_ could be considered a _loop mechanism_ ... but this would be too much :D)
ShinTakezou
Recursion is a boomerang!!! Or the hookshot!
maxwellb
Anti-goto talk is just propaganda.
BobbyShaftoe
-1 the answer has a loop in it.
JeremyP
+13  A: 

On the assumption that you are using 32 bit unsigned integers, the 48th Fibonacci number will cause an integer overflow. That makes it perfectly feasible to use a lookup table with all the values precalculated (by hand).

JeremyP
+1 for another solution (only said in comment). To show a possible code would be interesting to stress how the recursive solution, even though recursion may sound alien to him, is the shortest and more intuitive. ... (instead of calc by hand, he could use [this](http://81.167.229.63/~srbzorg/fibonaccigenerator.php) the link comes from wikipedia)
ShinTakezou
+1 for pointing out the incredible finitude of the problem and thus the optimal solution. A 192 byte table is probably even smaller than the code would be...not to mention a damn lot faster.
R..
@R: yes, and if 64 bit integers are used, there are still only 94 numbers before you get to overflow.
JeremyP
A: 

Recursion must be the answer dear! even i am an ameature and i think that recursion is the only other way to do that.

fahad
+5  A: 

use http://www.research.att.com/~njas/sequences/b000045.txt as a data file ;)

OJW