A Vampire number is a composite natural number with an even number of digits that can be factored into two natural numbers each with half as many digits as the original number and not both with trailing zeros, where the two factors contain precisely all the digits of the original number, in any order of counting multiplicity.
Example: 1260 = 21 × 60 (where, 21 and 60 contain precisely all the digits of the number)
Thus, 1260 is a Vampire number.
Accept two positive integers m and n, where m < n and values of both ‘m’ and ‘n’ must be >= 1000 and <= 9999 as user input. Display all Vampire numbers that are in the range between m and n (both inclusive) and output them along with the frequency, in the format specified below:
Test your program for the following data and some random data:
Example 1
INPUT:
m = 1002
n = 1640
OUTPUT:
THE VAMPIRE NUMBERS ARE:
1260 1395 1435 1530
FREQUENCY OF VAMPIRE NUMBER IS: 4
Example 2
INPUT:
m = 1810
n = 7800
OUTPUT:
THE VAMPIRE NUMBERS ARE:
1827 2187 6880
FREQUENCY OF VAMPIRE NUMBER IS: 3
Example 3
INPUT:
m = 8105
N = 9999
OUTPUT:
THE VAMPIRE NUMBERS ARE:
NIL
FREQUENCY OF VAMPIRE NUMBER IS: 0
Example 4
INPUT:
m = 174
n = 4500
OUTPUT:
INVALID INPUT
import java.util.Scanner;
class Vampire{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("m = ");
int m = Integer.parseInt(in.nextLine());
System.out.print("n = ");
int n = Integer.parseInt(in.nextLine());
if(m < 1000 || n < 1000 || m > 9999 || n > 9999){
System.out.println("INVALID INPUT");
return;
}
int count = 0;
System.out.println("THE VAMPIRE NUMBERS ARE:");
for(int i = m; i <= n; i++){
if(isVampire(i)){
count++;
System.out.print(i + " ");
}
}
if(count == 0)
System.out.print("NIL");
System.out.println("\nFREQUENCY OF VAMPIRE NUMBER IS: " + count);
}
public static boolean isVampire(int num){
String number = String.valueOf(num);
int len = number.length();
if(len % 2 != 0)
return false;
for(int i = (int)Math.pow(10, len / 2 - 1); i < Math.pow(10, len / 2); i++){
int factor1 = i;
int factor2 = num / factor1;
if(factor1 * factor2 == num){
String factors = String.valueOf(factor1) + String.valueOf(factor2);
char originalChars[] = new char[number.length()];
for(int j = 0; j < number.length(); j++)
originalChars[j] = number.charAt(j);
char factorsChars[] = new char[factors.length()];
for(int j = 0; j < factors.length(); j++)
factorsChars[j] = factors.charAt(j);
sort(originalChars);
sort(factorsChars);
if(equals(originalChars, factorsChars))
return true;
}
}
return false;
}
public static void sort(char a[]){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a.length - 1 - i; j++){
if(a[j] > a[j + 1]){
char temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
public static boolean equals(char a[], char b[]){
if(a.length != b.length)
return false;
for(int i = 0; i < a.length; i++){
if(a[i] != b[i])
return false;
}
return true;
}
}