# compute very large Fibonacci number

Discussion in 'Software Development' started by sillyboy, Mar 3, 2009.

Not open for further replies.

Joined:
May 30, 2007
Messages:
27
compute the n-th Fibonacci number using char, malloc; need help to fix the code:

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

int BigFib(int n, char *ans)
{
int i;
char *t;
double d = (double) (0.30103 * n + 10);
char *old = (char *)malloc(d);
char *previous = (char *)malloc(d);
char *next = (char *)malloc(d);
if(!old || !previous || !next)
return 1;
old = '0';
previous = '1';
next = '1';
for(i=1; i<n; i++)
{
t = old;
old = previous;
previous = next;
next = t;
ans = previous;
}

static void add(char *a, char *b, char *ans)
{
int i=0, x=0, y;
int left, right, n;
n = (int) strlen(a);
for(left = 0, right = n - 1; left < right; left++, right--)
swap(a
, a
);
n = (int) strlen(b);
for(left = 0, right = n - 1; left < right; left++, right--)
swap(b
, b
);
while(a!='\0' && b!='\0')
{
y = (a-48) + (b-48) + x;
x = y/10;
y = y%10;
ans = y + 48;
i++;
}
while(i<strlen(a))
{
y = (a-48) + x;
x = y/10;
y = y%10;
ans = y + 48;
i++;
}
while(i<strlen(b))
{
y = (b-48) + x;
x = y/10;
y = y%10;
ans = y + 48;
i++;
}
if(x!=0)
ans[i++] = x + 48;
n = (int) strlen(ans);
for(left = 0, right = n - 1; left < right; left++, right--)
swap(ans
, ans
);
}
free(old);
free(previous);
free(next);
return 0;
}

int main (int argc, char*argv[])
{
int n;
char *ans;
BigFib(n, ans);
return 1;
}​

As Seen On