Santosh Krisnan <
[email protected]>
wrote:
# hello all,
#
# I fiddled with BASIC in the early 90s but left it
# at that. Now I am trying to learn C. I tried to
# solve an exercise in my book, but it failes to
# compile. Can anyone tell me what the error messages
# mean & what I should do?
I would remember my combinatorial math and look up
the formula for a noniterative computation of Fn.
F(n) = ( ((1+sqrt(5))/2)^n - ((1-sqrt(5))/2)^n ) /
sqrt(5)
Thanks. to be frank I'm not very tht strong in math,
but I implementad your formula and it's giving
different results to the earlier method, for large fib
values. I'm giving the src and sample output below.
did I do both correctly? If so which of the two is
correct? I'd be greatful if you can respond.
/* straightforward method */
#include <stdio.h>
double calc_fib(unsigned long);
int main(void)
{
int n;
unsigned long fibn;
double fibn_value;
printf("Enter fibonacci number: ");
n = scanf("%lu", &fibn);
if(n != 1) return 1;
fibn_value = calc_fib(fibn);
printf("\nThe %ld fibonacci number is %f\n", fibn,
fibn_value);
return 0;
}
double calc_fib(unsigned long fibn)
{
unsigned long counter;
double fibn_value = 1;
double previous1 = 1;
double previous2 = 0;
if(fibn == 1) return (double) 0;
else if(fibn == 2) return (double)1;
for(counter = 3; counter <= fibn; counter++) {
fibn_value = previous1 + previous2;
previous2 = previous1;
previous1 = fibn_value;
}
return fibn_value;
}
/* SM Ryan's method */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
long double fibnld(unsigned long);
int main(int argc, char **argv) {
long double fib;
unsigned long nfib;
if(argc < 2) return EXIT_FAILURE;
else {
errno = 0;
nfib = strtoul(argv[1], NULL, 0);
if(errno == ERANGE || nfib == 0) {
puts("range error.");
return EXIT_FAILURE;
}
else {
fib = fibnld(nfib);
printf("The %lu fibonacci number is: %Lf\n",
nfib, fib);
}
}
return 0;
}
long double fibnld(unsigned long nfib) {
const long double sqr_five = sqrtl(5);
long double tmp1 = (1 + sqr_five) / 2;
long double tmp2 = (1 - sqr_five) / 2;
tmp1 = powl(tmp1, nfib);
tmp2 = powl(tmp2, nfib);
tmp1 -= tmp2;
tmp1 /= sqr_five;
return tmp1;
}