Advertisement
nazar_art

VampireNumber

Jun 8th, 2013
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1. /*
  2.  * Find all 4-digit vampire numbers
  3.  */
  4. public class VampireNumber {
  5.  
  6.     /**
  7.      * Algorithm for find all 4-digit vampire numbers
  8.      *
  9.      */
  10.     public static void main(String[] args) {
  11.        
  12.         int[] startDigit = new int[4];
  13.         int[] productDigit = new int[4];
  14.         for (int num1 = 10; num1 <= 99; num1++)
  15.             for (int num2 = num1; num2 <= 99; num2++) {
  16.                 // Pete Hartley's theoretical result:
  17.                 // If x·y is a vampire number then
  18.                 // x·y == x+y (mod 9)
  19.                 if ((num1 * num2) % 9 != (num1 + num2) % 9)
  20.                     continue;
  21.                 int product = num1 * num2;
  22.                 startDigit[0] = num1 / 10;
  23.                 startDigit[1] = num1 % 10;
  24.                 startDigit[2] = num2 / 10;
  25.                 startDigit[3] = num2 % 10;
  26.                 productDigit[0] = product / 1000;
  27.                 productDigit[1] = (product % 1000) / 100;
  28.                 productDigit[2] = product % 1000 % 100 / 10;
  29.                 productDigit[3] = product % 1000 % 100 % 10;
  30.                 int count = 0;
  31.                 for (int x = 0; x < 4; x++)
  32.                     for (int y = 0; y < 4; y++) {
  33.                         if (productDigit[x] == startDigit[y]) {
  34.                             count++;
  35.                             productDigit[x] = -1;
  36.                             startDigit[y] = -2;
  37.                             if (count == 4)
  38.                                 System.out.println(num1 + " * " + num2 + " : "
  39.                                         + product);
  40.                         }
  41.                     }
  42.             }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement