-3

I have a simple problem, but because this "programming language" I am using is 32-bit and only supports basic functions such as addition, subtraction, multiplication, division, and concatenation (literally that's it), I am having some trouble.

For the input, I have a 16 digit number like so: 3334,5678,9523,4567

I want to then subtract 2 other random 16 digit numbers from this number and check if the first and last digits are 1.

For example, if the two other numbers are 1111,1111,1111,1111 and 1234,5678,9123,4565. My final number would be: 0988,8888,9288,8891.

Here, the last number is 1, but the first number is 0, so the test would fail.

The issue is with 32-bit systems, there are massive errors due to not enough precision provided by the bits. What are some ways to bypass this issue?

Rui Nian
  • 2,544
  • 18
  • 32

1 Answers1

0

If you're using a language like C or Java you should be able to use a long to create a 64 bit integer. If that's not possible you could divide the numbers into two 32 bit numbers, one to hold the upper half and one to hold the lower half.

Something like this:

//Each half is 8 digits to represent 8 of the 16
//Because of this each half should be less than 100000000
int upperHalf = 33345678;
int lowerHalf = 95234567;

//randomInt represents a function to generate a random
//integer equal to or greater than 0 and less than the
//argument passed to it
int randUpperHalf = randomInt(100000000);
int randLowerHalf = randomInt(100000000);

int lowerHalf = lowerHalf - randLowerHalf;

//If lowerHalf was a negative number you need to borrow from the upperHalf
if (lowerHalf < 0) {
    upperHalf = upperHalf - 1;
    lowerHalf = lowerHalf + 100000000;
}

upperHalf = upperHalf - randUpperHalf;

//Check that the first and last digits are 1
if ((upperHalf / 100000000) == 1 && (lowerHalf % 10) == 1) {
    //The first and last digits are 1
}

Edit: Comments have been added to explain the code better. (lowerHalf % 2) == 1 has been changed to (lowerHalf % 10) == 1 and should now be able to tell if the number ends in a 1.

Garrett
  • 11
  • 1
  • This doesn't work. And (lowerHalf %2) only shows the number is odd, not ending in 1. – WJS May 26 '20 at 01:53