Advertisement
binibiningtinamoran

SumOfAllDigitsValidator

Aug 22nd, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. // A number is considered valid if and only if the sum of all its digits is divisible by 7
  2. // and the product of all its digits is divisible by 5.
  3.  
  4. public class SumOfDigitsValidator {
  5.  
  6.     public static void main(String []args) {
  7.  
  8.         int count = 0;
  9.  
  10.         for (int i=0; i <= 9999; i++) {
  11.             if (isValidNumber(sumOfAllDigits(i), productOfAllDigits(i))) {
  12.                 count++;
  13.             }
  14.         }
  15.  
  16.         System.out.printf("\nThere are exactly %,d valid numbers between 0 and 9999.\n",count);
  17.     }
  18.  
  19.     public static int sumOfAllDigits(int entry) {
  20.         return sumOfAllDigitsHelper(entry,0);
  21.     }
  22.  
  23.     private static int sumOfAllDigitsHelper(int entry, int sum) {
  24.         if (entry == 0) {
  25.             return sum;
  26.         }
  27.         sum += entry % 10;
  28.         return sumOfAllDigitsHelper(entry/10, sum);
  29.  
  30.     }
  31.  
  32.     public static int productOfAllDigits(int entry) {
  33.         return productOfAllDigitsHelper(entry,1);
  34.     }
  35.  
  36.     private static int productOfAllDigitsHelper(int entry, int product) {
  37.         if (entry == 0) {
  38.             return product;
  39.         }
  40.         product *= entry % 10;
  41.         return productOfAllDigitsHelper(entry/10, product);
  42.     }
  43.  
  44.     private static boolean isValidNumber(int sum, int product) {
  45.         return sum % 7 == 0 && product % 5 == 0;
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement