Program opened below. You can scroll through the algorithm, Java code and output.
Program 81
Vampire Number
Question
A vampire number has an even number of digits and can be factored into two numbers with half as many digits whose combined digits exactly match the original number; both fangs must not end in zero.
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input a positive integer N.
Step 4: Validate the input values and display an error message if they are outside the permitted range.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: Check that N has an even number of digits.
Step 7: Generate possible factors with half as many digits.
Step 8: For each factor pair a and b where a*b=N, reject pairs where both end in zero.
Step 9: Sort the digits of N and of the concatenation of a and b.
Step 10: If the digit sets match, report the pair and that N is a vampire number.
Step 11: If no pair is found, report not a vampire number.
Step 12: Stop.
Java program
Javaimport java.util.*;
class VampireNumber {
static String sortDigits(String s) {
char[] a = s.toCharArray();
Arrays.sort(a);
return new String(a);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String digits = String.valueOf(n);
if (n < 10 || digits.length() % 2 != 0) {
System.out.println("NOT A VAMPIRE NUMBER");
return;
}
int half = digits.length() / 2;
int low = (int) Math.pow(10, half - 1), high = (int) Math.pow(10, half) - 1;
boolean found = false;
for (int a = low; a <= high && !found; a++) {
if (n % a != 0) {
continue;
}
int b = n / a;
if (b < low || b > high || (a % 10 == 0 && b % 10 == 0)) {
continue;
}
if (sortDigits("" + a + b).equals(sortDigits(digits))) {
System.out.println("VAMPIRE NUMBER: " + a + " x " + b);
found = true;
}
}
if (!found) {
System.out.println("NOT A VAMPIRE NUMBER");
}
}
}Sample output
Input: 1260
Output:
VAMPIRE NUMBER: 21 x 60