So I am working on a competitive programming problem where you take two numbers base two and base three, and then do some operations on them. I got the code implementing correctly, however it doesn't work with large inputs. For example, when I try to input 10010111011100101101100011011 (base two) and 211010102022001220 (base three). This is because I am inputting them as a regular integer, then converting them to their actual base 10 value.
This is my conversion function (just for bases 2 and 3)
int conv(int base, ll n){
int result = 0;
if(base == 2){
int a = 0;
while(n > 0){
if(n % 2 == 1){
result += pow(2, a);
}
a++;
n /= 10;
}
return result;
}
else if(base == 3){
int a = 0;
while(n > 0){
result += (n%10)%3 * pow(3, a);
a++;
n /= 10;
}
return result;
}
return result;
When I run this function on really small numbers like conv(2, 1010), it works; I get 10 (converting 1010 base 2 into base 10)
However, if I want to take in 10010111011100101101100011011(base 2), my code doesn't seem to work. Is there any other way I can do this?
Depending on what particular operations you want to perform on your base-2 and base-3 numbers, it may be feasible to just operate on string values. The advantage is that you are virtually unbounded.
Read your input numbers as strings. Write a function to verify that a given string is a valid number in a given base. Then write those operations to work on strings. It will be easy for addition and subtraction, but will require a few more steps for multiplication and division. If you need to handle trigonometry and transcendental functions, then it will be a difficult but doable math problem. Basically you want to implement exactly the steps you undergo when you perform the operations by hand, complete with carrying and borrowing.