C++ Long Division -
whilst working on personal project of mine, came across need divide 2 large arbitrary numbers (each number having 100 digits). wrote out basic code division (i.e., answer = a/b, , b imputed user)and discovered has precision of 16 digits! may obvious @ point im not coder!
so searched internet , found code that, far can tell, uses traditional method of long division making string(but honest im not sure im quite confused it). upon running code gives out incorrect answers , wont work @ if a>b. im not sure if there's better way solve problem method in code below!? maybe there's simpler code??
so need write code, in c++, divide 2 large numbers. or suggestions appreciated!
#include <iostream> #include <iomanip> #include <cmath> using namespace std; //avoids having use std:: cout/cin int main (int argc, char **argv) { string dividend, divisor, difference, a, b, s, tempstring = ""; // , b used store dividend , divisor. int quotient, inta, intb, diff, tempint = 0; char d; quotient = 0; cout << "enter dividend? "; //larger number (on top) cin >> a; cout << "enter divisor? "; //smaller number (on bottom) cin >> b; //making strings same length adding 0's beggining of string. while (a.length() < b.length()) = '0'+a; // has less digits b add 0's while (b.length() < a.length()) b = '0'+b; // b has less digits add 0's inta = a[0]-'0'; // getting first digit in both strings intb = b[0]-'0'; //if a<b print remainder out (a) , return 0 if (inta < intb) { cout << "quotient: 0 " << endl << "remainder: " << << endl; } else { = '0'+a; b = '0'+b; diff = intb; //s = b; // while ( s >= b ) { (int = a.length()-1; i>=0; i--) // subtraction until end of string { inta = a[i]-'0'; // converting ascii int, used munipulation intb = b[i]-'0'; if (inta < intb) // borrow if needed { a[i-1]--; //borrow next digit a[i] += 10; } diff = a[i] - b[i]; char d = diff+'0'; s = d + s; //this + appending 2 strings, not performing addition. } quotient++; = s; // strcpy (a, s); } while (s >= b); // fails after dividing 3 x's cout << "s string: " << s << endl; cout << "a string: " << << endl; cout << "quotient: " << quotient << endl; //cout << "remainder: " << s << endl; } system ("pause"); return 0; cin.get(); // allows user enter variable without instantly ending program cin.get(); // allows user enter variable without instantly ending program
}
there better methods that. subtractive method arbitrarily slow large dividends , small divisors. canonical method given algorithm d in knuth, d.e., the art of computer programming, volume 2, i'm sure find online. i'd astonished if wasn't in wikipedia somewhere.
Comments
Post a Comment