Problem Description: When you divide the successive powers of 10 by 13 you get the following remainders of the integer divisions:
1, 10, 9, 12, 3, 4.
Then the whole pattern repeats.
Hence the following method: Multiply the right most digit of the number with the left most number in the sequence
shown above, the second right most digit to the second left most digit of the number in the sequence. The cycle goes on and you sum all these products. Repeat this process until the sequence of sums is stationary.
...........................................................................
Example: What is the remainder when 1234567 is divided by 13?
7×1 + 6×10 + 5×9 + 4×12 + 3×3 + 2×4 + 1×1 = 178
We repeat the process with 178:
8x1 + 7x10 + 1x9 = 87
and again with 87:
7x1 + 8x10 = 87
...........................................................................
From now on the sequence is stationary and the remainder of 1234567 by 13 is the same as the remainder of 87 by 13: 9
Call thirt the function which processes this sequence of operations on an integer n (>=0). thirt will return the
stationary number.
thirt(1234567) calculates 178, then 87, then 87 and returns 87.
thirt(321) calculates 48, 48 and returns 48
Level: 7kyu
Link to Kata: A Rule of Divisibility by 13
This Kata is based on a mathematical result of division by 13. We start solving this Kata by initializing an array "base_arr" to all the remainder which we get when we divide successive powers of 10 by 13. Then we declare a variable "j" equal to 0 and another variable "sum" equal to 0. We start looping through a while loop and multiply every digit on the index with a digit from the "base_arr". Then we increment the value of index and "j" which is an index for base array. If "j" becomes equal to 6 then we reinitialize it to 0. We add the product in every step to "sum" variable.
Once we are done with the while loop, we check the value of sum and compare it with the initial value of input. If it is the same then we break out from the loop or else we assign the value of sum to input variable and continue with the above operation again.
In the end we return the value of input variable.
Here is a link to the code: Kata Day 20
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment