Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // A number is considered valid if and only if the sum of all its digits is divisible by 7
- // and the product of all its digits is divisible by 5.
- public class SumOfDigitsValidator {
- public static void main(String []args) {
- int count = 0;
- for (int i=0; i <= 9999; i++) {
- if (isValidNumber(sumOfAllDigits(i), productOfAllDigits(i))) {
- count++;
- }
- }
- System.out.printf("\nThere are exactly %,d valid numbers between 0 and 9999.\n",count);
- }
- public static int sumOfAllDigits(int entry) {
- return sumOfAllDigitsHelper(entry,0);
- }
- private static int sumOfAllDigitsHelper(int entry, int sum) {
- if (entry == 0) {
- return sum;
- }
- sum += entry % 10;
- return sumOfAllDigitsHelper(entry/10, sum);
- }
- public static int productOfAllDigits(int entry) {
- return productOfAllDigitsHelper(entry,1);
- }
- private static int productOfAllDigitsHelper(int entry, int product) {
- if (entry == 0) {
- return product;
- }
- product *= entry % 10;
- return productOfAllDigitsHelper(entry/10, product);
- }
- private static boolean isValidNumber(int sum, int product) {
- return sum % 7 == 0 && product % 5 == 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement