Assignment 3

 

In Lab Test 2, we say that a 19-digit non-negative integer, which can not be stored in an ordinary int type, can be implemented using an array. For example, the integer 9876543210987654321 can be stored as follows:

a:

1

2

3

4

5

6

7

8

9

0

1

2

3

4

5

6

7

8

9

 

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

In this assignment, you are to create a structure called HugeInteger that can store 30-digit integers, both positive and negative:

struct HugeInteger {

   int sign;   // 1 means negative, 0 otherwise

   int a[30]; // stores the digits as shown above

};      // Recall from your 計概 that this implementation is

// called sign-and-magnitude.

 

3.1.        Write a function void HI_set(HugeInteger &i, char* p) to initialize i to an integer represented as a string p. For example, the example above may be the result of calling HI_set(i, "9876543210987654321"). Note that the string may denote a negative number. In that case, the sign should be set to -1.

3.2.        Write a function void HI_add(const HugeInteger &x, const HugeInteger &y, HugeInteger& z) to compute z = x + y.

3.3.        Write a function void HI_subtract(const HugeInteger &x, const HugeInteger &y, HugeInteger &z) to compute z = x - y.

3.4.        Write a function void HI_multiply(const HugeInteger &x, const HugeInteger &y, HugeInteger &z) to compute z = x * y. If the result is longer that 30 digits, overflow will occur.

3.5.        Write a function void HI_output(const HugeInteger &i) to print out the number i on cout.

3.6.        Write a test driver (i.e., a main function) to test your functions.

3.7.        Of course, you can also try the more difficult HI_divide( ) and HI_mod( ), if you feel you are up to the task.