1. Computer problem? Tech Support Guy is completely free -- paid for by advertisers and donations. Click here to join today! If you're new to Tech Support Guy, we highly recommend that you visit our Guide for New Members.

compute very large Fibonacci number

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

Thread Status:
Not open for further replies.
Advertisement
  1. sillyboy

    sillyboy Thread Starter

    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++)
    {
    add(old, previous, next);
    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
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 733,556 other people just like you!

Thread Status:
Not open for further replies.

Short URL to this thread: https://techguy.org/806009