-1

So I have to solve this Problem: We assume that R1, R2, R3, and R4 have an integer valued resistance. After input of the four values, the program should output the result arithmetically rounded to the next integer. You may for this exercise assume that the builtin integer division rounds towards zero for all operands. Use of floating point arithmetic is not allowed. Changing to big number library is not possible.

and this is my code:

int R1;
int R2;
int R3;
int R4;

std::cin >> R1;
std::cin >> R2;
std::cin >> R3;
std::cin >> R4; 

int R12 = R1 + R2;
int R34 = R3 + R4;

unsigned int Rtot = ((2*(R12 * R34) / (R12 + R34) + 1)) / 2 ;

std::cout << Rtot ;

return 0;

but if I use big numbers (8000 24000 16000 32000) I get a problem with the overflow. Any ideas? Doesn't work with unsigned, I tried. I'm guessing to solve it with modulus, but no idea how.

2 Answers2

2

You could either:

  1. Increase the bytes of your representative resistor value by using long int or long long int.
  2. Reduce your resistor by the highest multiple of 10 and do calculation. Then either re multiply it by the value you reduced by, or return the low value and a multiplier for the user to use. In the example given (8000 24000 16000 32000) you could reduce all values by 1000, without loosing data, do the maths then multiply by 1000 at the end or return the answer and the multiplier.
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
0

assuming you cannot change the int type, you can change the formula used to compute the result. In numerical computing it’s common that algebraically equivalent expressions turn out having totally different numerical properties.

in this case you may rewrite yours as

(1+r-a^2/r)/2

where R12:=r+a,R34:=r-a

if a^2 overflows ( compare against numeric_limit::max before multiplying ) replace that term with 4((a/2)^2)/r, and so on until does not ...

PS. writing this from an ipad, will add more later .... (we can do better)

Massimiliano Janes
  • 5,524
  • 1
  • 10
  • 22