vendredi 3 juillet 2020

Is an array of digits an efficient way to create numbers too long for the default variable types?

There is already a question on how to create extra-large numbers of that I can roughly remember what it said (I couldn't find the original thread, but it is on StackOverflow). The recommendation that stuck to me the most was the one that said to use a linked list, a type of structure, for using numbers that are too large. But, I was having so much trouble actually using it that I just made a short int array of digits. My friend, who I consider a better programmer than me, also told me that linked lists are the way to go, but I do not see what is wrong with the array system.

Here is the actual code (not that important but just in case)

It's a script that calculates factorial, I needed the extra digits because factorials get too big too fast.

#include <iostream>
using namespace std;

void factorial(int n, int s = 100)
{
    cout << "number: ";
    //establish return array
    short int x[s] = {1};
    short int a[s];
    //for every number from 2 (1 include previously) to n
    for (int i = 2; i <= n; i++)
    {
        
        for (int j = 0; j < s; j++)
        {
            x[j] *= i;
            a[j] = x[j];
        }

        for (int j = s - 1; j >= 1; j--)
        {
            x[j] = a[j - 1] / 10 + a[j] % 10;
            if (x[j] > 9)
            {
                x[j + 1] += x[j] / 10;
                x[j] = x[j] % 10;
            }
        }

        x[0] %= 10;

        for (int j = 0; j < s; j++)
        {
            if (x[j] > 9)
            {
                x[j + 1] += x[j] / 10;
                x[j] = x[j] % 10;
            }
        }
    }

    //flip array
    int start = 0;
    int end = s - 1;
    while (start < end) 
    { 
        int temp = x[start];  
        x[start] = x[end]; 
        x[end] = temp; 
        start++; 
        end--; 
    }

    //remove unnecesary zeroes
    int flag = 0;
    for (int i = 0; i < s; i++)
    {
        if (x[i] == 0)
            flag = i;
        else
            break;
    }
    for (int i = flag + 1; i < s; i++)
    {
        cout << x[i];
    }
    cout << "\n";
}

int main()
{
    int n;
    int s;
    cout << "type in a number\t";
    cin >> n;
    //get s based off n
    int dn = double(n);
    s = 0.007 * (dn * dn) + 0.94 * dn + 1;
    cout << "digits: " << s << "\n";
    factorial(n, s);
}

Aucun commentaire:

Enregistrer un commentaire