# Khan/khan-exercises

### Subversion checkout URL

You can clone with
or
.
Fetching contributors…
Cannot retrieve contributors at this time
65 lines (60 sloc) 4.49 KB
 Subtracting Decimals
randRange( 1, 3 ) randRange( 1001, 9999 ) / pow( 10, DECIMAL_A) randRange(2,4) randRange( 101, 999 ) / pow( 10, DECIMAL_B) digits( round( A * pow( 10, DECIMAL_B))) digits( round( B * pow( 10, DECIMAL_B))) createLongSubtractionTable( A_ARRAY, B_ARRAY) TABLE.result / pow( 10, DECIMAL_B ) TABLE.borrow

A - B = ?

RESULT

First we need to line up the decimal points.

Now we need to make sure that all the digits in the top number are greater than or equal to the digit below it.

For the first digit, A_ARRAY[0] is less then B_ARRAY[0], so we'll have to borrow.

A_ARRAY[1] - 1 = A_ARRAY[1]-1, A_ARRAY[0] + 10 = A_ARRAY[0]+10

For the second digit, A_ARRAY[1]-BORROW[1] is less then B_ARRAY[1], so we'll have to borrow.

A_ARRAY[2] - 1 = A_ARRAY[2]-1, A_ARRAY[1]-BORROW[1] + 10 = A_ARRAY[1]-BORROW[1]+10

For the third digit, A_ARRAY[2]-BORROW[2] is less then B_ARRAY[2], so we'll have to borrow.

A_ARRAY[3] - 1 = A_ARRAY[3]-1, A_ARRAY[2]-BORROW[2] + 10 = A_ARRAY[2]-BORROW[2]+10

For the fourth digit, A_ARRAY[3]-BORROW[3] is less then B_ARRAY[3], so we'll have to borrow.

A_ARRAY[4] - 1 = A_ARRAY[4]-1, A_ARRAY[3]-BORROW[3] + 10 = A_ARRAY[3]-BORROW[3]+10

For the fifth digit, A_ARRAY[4]-BORROW[3] is less then B_ARRAY[4], so we'll have to borrow.

A_ARRAY[5] - 1 = A_ARRAY[5]-1, A_ARRAY[4]-BORROW[4] + 10 = A_ARRAY[4]-BORROW[4]+10

For the sixth digit, A_ARRAY[5]-BORROW[5] is less then B_ARRAY[5], so we'll have to borrow.

A_ARRAY[6] - 1 = A_ARRAY[6]-1, A_ARRAY[5]-BORROW[5] + 10 = A_ARRAY[5]-BORROW[5]+10

All the top digits are greater than or equal to all the bottom digits, so we can start subtracting.

First digit: A_ARRAY[0] + ( 10 * BORROW[1] ) - B_ARRAY[0] = A_ARRAY[0] + ( 10 * BORROW[1] ) - B_ARRAY[0]

Second digit: A_ARRAY[1] - BORROW[1] + ( 10 * BORROW[2] ) - B_ARRAY[1] = A_ARRAY[1] - BORROW[1] + ( 10 * BORROW[2] ) - B_ARRAY[1]

Third digit: A_ARRAY[2] - BORROW[2] + ( 10 * BORROW[3] ) - B_ARRAY[2] = A_ARRAY[2] - BORROW[2] + ( 10 * BORROW[3] ) - B_ARRAY[2]

Fourth digit: A_ARRAY[3] - BORROW[3] + ( 10 * BORROW[4] ) - B_ARRAY[3] = A_ARRAY[3] - BORROW[3] + ( 10 * BORROW[4] ) - B_ARRAY[3]

Fifth digit: A_ARRAY[4] - BORROW[4] + ( 10 * BORROW[5] ) - B_ARRAY[4] = A_ARRAY[4] - BORROW[4] + ( 10 * BORROW[5] ) - B_ARRAY[4]

Sixth digit: A_ARRAY[5] - BORROW[5] + ( 10 * BORROW[6] ) - B_ARRAY[5] = A_ARRAY[5] - BORROW[5] + ( 10 * BORROW[6] ) - B_ARRAY[5]

Seventh digit: A_ARRAY[6] - BORROW[6] - B_ARRAY[6] = A_ARRAY[6] - BORROW[6] - B_ARRAY[6]

Now bring down all the other digits.