JavaAlgorithms/Maths/VampireNumber.java

79 lines
2.1 KiB
Java
Raw Normal View History

package Maths;
import java.util.ArrayList;
import java.util.Collections;
/**
2020-10-24 18:23:28 +08:00
* n number theory, a vampire number (or true 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 zeroes, where the two factors contain
* precisely all the digits of the original number, in any order, counting multiplicity. The first
* vampire number is 1260 = 21 × 60. *
*
2020-10-24 18:23:28 +08:00
* <p>* link: https://en.wikipedia.org/wiki/Vampire_number *
*
* <p>
*/
public class VampireNumber {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
2020-10-24 18:23:28 +08:00
test(10, 1000);
}
2020-10-24 18:23:28 +08:00
static void test(int startValue, int stopValue) {
int countofRes = 1;
StringBuilder res = new StringBuilder();
2020-10-24 18:23:28 +08:00
for (int i = startValue; i <= stopValue; i++) {
for (int j = i; j <= stopValue; j++) {
// System.out.println(i+ " "+ j);
if (isVampireNumber(i, j, true)) {
countofRes++;
res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i * j + ")" + "\n");
}
}
}
System.out.println(res);
}
static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) {
// this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for
// example
// 126 = 6 x 21
if (noPseudoVamireNumbers) {
if (a * 10 <= b || b * 10 <= a) {
return false;
}
}
2020-10-24 18:23:28 +08:00
String mulDigits = splitIntoDigits(a * b, 0);
String faktorDigits = splitIntoDigits(a, b);
2020-10-24 18:23:28 +08:00
return mulDigits.equals(faktorDigits);
}
2020-10-24 18:23:28 +08:00
// methode to Split the numbers to Digits
static String splitIntoDigits(int num, int num2) {
2020-10-24 18:23:28 +08:00
StringBuilder res = new StringBuilder();
2020-10-24 18:23:28 +08:00
ArrayList<Integer> digits = new ArrayList<>();
while (num > 0) {
digits.add(num % 10);
num /= 10;
}
while (num2 > 0) {
digits.add(num2 % 10);
num2 /= 10;
}
Collections.sort(digits);
for (int i : digits) {
res.append(i);
}
2020-10-24 18:23:28 +08:00
return res.toString();
}
2020-05-13 06:01:38 +08:00
}