1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| package utilitaire;
import java.math.BigInteger;
/**
* @author Philippe Bourdages
*/
public class NombreLacroix {
private static BigInteger number;
private static String numberSquared;
private static Integer qtyChar;
private static Integer qtyCharSquared;
private static BigInteger nbrToSubtract;
private static BigInteger nbrSubtracting;
private static BigInteger result;
private static Boolean valid;
/**
* Validation d'un nombre Lacroix.
*
* @return Boolean
* @param arg BigInteger
*/
public static synchronized boolean isNombreLacroix(final BigInteger arg) {
number = arg;
valid = false;
numberSquared = number.pow(2).toString();
qtyChar = number.toString().length();
qtyCharSquared = numberSquared.length();
nbrToSubtract = new BigInteger(numberSquared.substring(0, qtyChar));
nbrSubtracting = new BigInteger(numberSquared.substring(qtyChar));
/*Élimination des nombres lacroix qui résultent d'une
soustractions par zéro et un. Ex: 1001 et 1000*/
if (nbrSubtracting.compareTo(BigInteger.ONE) > 0) {
result = nbrToSubtract.subtract(nbrSubtracting);
/*Comparaison du nombre de départ et du nombre soustrait.
S'ils sont égaux, alors c'est un nombe lacroix*/
if (number.compareTo(result) == 0) {
valid = true;
}
}
return valid;
}
/*
* Exemple d'utilisation de la classe...
*/
public static void main(final String[] args) {
long start = System.nanoTime();
BigInteger i, iAdd, iMax;
iAdd = new BigInteger("1");
iMax = new BigInteger("2000000");
for (i = new BigInteger("4"); i.compareTo(iMax) <= 0; i = i.add(iAdd)) {
if (NombreLacroix.isNombreLacroix(i)) {
System.out.println(i);
}
}
long end = System.nanoTime();
long elapsedNanoSeconds = end - start;
System.out.println("time elapsed:" + elapsedNanoSeconds);
}
} |
Partager