Divisibility and Digits
Two standard algorithms work on a single integer: testing whether it is evenly divisible by another integer, and taking its digits apart. A store gives each product a four-digit code, and a code is valid when the product of its digits is divisible by 4.
Division and remainder
For positive
int values, / gives the whole number of times the divisor fits, and % gives what is left over.int code = 4712;
System.out.println(code / 10);
System.out.println(code % 10);
This prints 471 and then 2. Dividing by 10 drops the last digit, and the remainder by 10 is the last digit. A remainder can't reach the divisor, so for a positive
x, x % 4 is a number from 0 through 3.The order of the operands matters.
56 % 4 is 0, since 4 divides 56. 4 % 56 is 4, since 56 doesn't fit into 4 at all. In a % b, the number being tested comes first.Taking the digits apart
A loop reads the last digit, multiplies it into a running product, and drops it, until no digits are left.
int left = code;
int product = 1;
while (left > 0)
{
product = product * (left % 10);
left = left / 10;
}
left at the check digit used product after
4712 2 2
471 1 2
47 7 14
4 4 56
0 (loop ends)
The digits come out from right to left. The digit has to be read before
left / 10 drops it, and the division has to happen on every pass, since it's what brings left down to 0. The product starts at 1, not 0, because a product that starts at 0 stays 0.The product is 56, and
product % 4 == 0 is true, so 4712 is a valid code. The digits of 3715 multiply to 105, which leaves 1 over, so 3715 isn't valid.One digit from the middle
The remainder by 10 only ever gives the last digit, so a digit further left has to be shifted there first by dividing. Orders at the store get six-digit numbers, and the thousands digit of the order number 582614 is
(582614 / 1000) % 10. The division gives 582, and its last digit is 2. In the other order, 582614 % 10 keeps only the 4, and dividing that by 1000 gives 0.