Casting Out Nines
Time Limit: 1000 ms Memory Limit: 65536 KiB
You must have heard of the great mathematician Leonardo da Pisa Fibonacci (1170-1240). Among the many algorithms that he described in his Liber Abaci book, (which was first published in 1202,) Fibonacci described the Casting Out Nines procedure for checking out addition, subtraction, and multiplication. According to historians, the procedure was transmitted to Europe by the Arabs, but was probably developed somewhere on the Indian subcontinent and is therefore sometimes also called “the Hindu check.”
“Casting out nines” is an elementary check of a multiplication which makes use of the congruence 10^x ≡ 1 (mod 9). Remember that when writing
x ≡ y (mod z) we’re actually saying that (x mod z) is equal to (y mod z).
Let a, b be natural numbers whose product is c. Let the sums of the digits of these numbers be ˉa,ˉb, and ˉc. Then a ≡ ˉa (mod 9), b ≡ˉb (mod 9), and c ≡ ˉc (mod 9). Furthermore a×b ≡ ˉa×ˉb (mod 9),and so ˉa ×ˉb ≡ ˉc (mod 9). So if c and ˉa ×ˉb are incongruent (mod 9), the multiplication has been done incorrectly.
For example, 12345 × 67890 = 838102050. The sum-of-digits of 12345 and 67890 are 15 and 30,respectively, and the product of these is 450. Similarly, the sum-of-digits of 838102050 is 27. And since 450 ≡ 27 ≡ 0 (mod 9), so the Hindu Check shows agreement.
As another example, say someone incorrectly calculates 13579×24680 = 334129720. Since ˉa×ˉb = 25 × 20 = 500 ≡ 5 (mod 9) whereas ˉc = 31 ≡ 4 (mod 9). So the multiplication is definitely incorrect.
The Hindu check can also be used to check on additions, since a + b ≡ ˉa +ˉb (mod 9).
Write a program that determines if a given addition or multiplication passes the Hindu Check or not.
Your program will be tested on one or more test cases. Each test case is specified on a separate input line. Each line is of the form:
Notice the ’.’ at the end of the line. ’a’, ’b’, and ’c’ are natural numbers. There are no spaces between the numbers and the symbols (’+’, ’*’, ’=’, and ’.’,) but trailing white-space may appear after the ’.’.
The last line of the input file, which is not part of the test cases, will have a single ’.’.
12345*67890=838102050. 13579*24680=334129720. 23+11=34. .
1. PASS 2. NOT! 3. PASS