Long exact numbers in C?

I am making a program that prints the first 100 numbers of Lucas (they are similar to Fibonacci), but the last few numbers don't fit into an unsigned long long int. I have tried using a long double, but it is not accurate and I am getting some differences from what I should be getting.

This is a homework task and my teacher specifically pointed out that we don't need to use any other library other than stdio.h.

I've tried making a method that adds strings as numbers, but that's far beyond experience and I sincerely doubt this is what we should be doing.

With inaccuracies, it looks something like this:

#include <stdio.h>

int main()
{
    long double firstNumber = 2;
    long double secondNumber = 1;
    long double thirdNumber;

    int i;
    for (i = 2; i <= 100; i += 1)
    {
        thirdNumber = secondNumber + firstNumber;
        firstNumber = secondNumber;
        secondNumber = thirdNumber;
        printf("%Lf, ", thirdNumber);
    }

    return 0;
}

      

+3


source to share


2 answers


It looks like all you need is an add-on. I see three ways to do this.



  • Unless you are prohibited from using libraries, you would use one of the many bigint libraries available.
  • Implementation of a row-based accumulator. Basically you are implementing the add method that you learned in 3rd class.
  • As a hack, if your highest number is roughly two unsigned long long ints

    , you can split your number into most significant digits and least significant digits. I would go this route.
+4


source


I used below to store really big numbers in an array. Paste the code below with some comments. Hope it helps.



#include<stdio.h>
int main()
{
    int t;
    int a[200]; //array will have the capacity to store 200 digits.
    int n,i,j,temp,m,x;

    scanf("%d",&t);
    while(t--)
    {
       scanf("%d",&n);
       a[0]=1;  //initializes array with only 1 digit, the digit 1.
       m=1;    // initializes digit counter

       temp = 0; //Initializes carry variable to 0.
       for(i=1;i<=n;i++)
       {
            for(j=0;j<m;j++)
            {
               x = a[j]*i+temp; //x contains the digit by digit product
               a[j]=x%10; //Contains the digit to store in position j
               temp = x/10; //Contains the carry value that will be stored on later indexes
            }
             while(temp>0) //while loop that will store the carry value on array.
             { 
               a[m]=temp%10;
               temp = temp/10;
               m++; // increments digit counter
             }
      }
              for(i=m-1;i>=0;i--) //printing answer
              printf("%d",a[i]);
              printf("\n");
    }
    return 0;
}

      

+1


source







All Articles