Division of a big number of 100 digits stored as string

送分小仙女□ 提交于 2019-12-07 05:04:56

问题


I have a 100 digit number stored as string. I want to divide this number with an integer less than 10. How do I efficiently divide a big integer stored as a string with an integer?


回答1:


You can check the big integer library.

You can use this library in a C++ program to do arithmetic on integers of size limited only by your computer's memory. The library provides BigUnsigned and BigInteger classes that represent nonnegative integers and signed integers, respectively. Most of the C++ arithmetic operators are overloaded for these classes, so big-integer calculations are as easy as:

#include "BigIntegerLibrary.hh"

BigInteger a = 65536;
cout << (a * a * a * a * a * a * a * a);

(prints 340282366920938463463374607431768211456)

Also check GMP




回答2:


@WasimThabraze - what is your understanding of the longhand division method? Since the divisor is less than 1/2 the size of an integer you can use something like this for each divide:

char array[10] = {9,8,7,6,5,4,3,2,1,0};

void divide(int dvsr)
{
int rem = 0;
int dvnd;
int quot;
int i;
    for(i = 0; i < (sizeof(array)/sizeof(array[0])) ; i++){
        dvnd = (rem * 10) + array[i];
        rem = dvnd % dvsr;
        quot = dvnd / dvsr;
        array[i] = quot;
    }
}

int main(void)
{
    divide(8);
    return (0);
}



回答3:


I hope this helps you because not all online judges allow BigIntegerLibrary.I have assumed for some arbitrary input.

string input="123456789";
int n=input.size();
string final(n,'0');
string::const_iterator  p=input.begin(),q=input.end();
string::iterator f=final.begin();

void divide(int divisor)
{
 int reminder = 0,dividend,quotient;

 /*repeatedly divide each element*/
 for(; p!=q ; p++,f++){
    dividend = (reminder * 10) + (*p-'0');
    reminder = dividend % divisor;
    quotient = dividend / divisor;
    *f = quotient + '0';
 }
 /*remove any leading zeroes from the result*/
 n = final.find_first_not_of("0");
 if (n != string::npos)
 {
    final = final.substr(n);
 }
 std::cout << final ;
}

int main(){
   int x;
   std::cin  >> x;
   divide(x);
   return 0;
}


来源:https://stackoverflow.com/questions/24579495/division-of-a-big-number-of-100-digits-stored-as-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!