Comment puis-je générer un entier n chiffres aléatoire en Java en utilisant la classe BigInteger?

StackOverflow https://stackoverflow.com/questions/3709521

  •  02-10-2019
  •  | 
  •  

Question

Je ne suis pas sûr sur la façon de générer un nombre entier de n chiffres aléatoire en Java en utilisant la classe BigInteger.

Était-ce utile?

La solution

private static Random rnd = new Random();

public static String getRandomNumber(int digCount) {
    StringBuilder sb = new StringBuilder(digCount);
    for(int i=0; i < digCount; i++)
        sb.append((char)('0' + rnd.nextInt(10)));
    return sb.toString();
}

Et puis vous pouvez l'utiliser:

new BigInteger(getRandomNumber(10000))

Autres conseils

D'après les documents, il est un constructeur de faire ce que vous voulez en Java 6: BigInteger (int, java.util.Random)

Pour cela, il vous suffit d'ajouter un chiffre-i.e. de 5000e choisis au hasard. Utilisez le constructeur de RNG à 4999 chiffres, l'ajouter le dernier via un processus aléatoire distinct. En fait, puisque vous voulez juste des performances échantillon pour les grandes valeurs, vous pouvez générer les bits, et virer de bord un peu sur la grande fin, plutôt que l'esclave à la notation décimale.

La façon la plus simple serait sans doute d'être remplir un tableau char [] avec 5000 chiffres aléatoires, convertir en une chaîne, puis appeler le constructeur BigInteger(String).

Si l'une de ces étapes, vous donne des problèmes, s'il vous plaît donner plus de détails.

Vous peut faire quelque chose comme ceci:

Random rng = new Random(); // But use one instance throughout your app
BigInteger current = BigInteger.ZERO;
for (int i = 0; i < 5000; i++) {
    BigInteger nextDigit = BigInteger.valueOf(rng.nextInt(10));
    current = current.multiply(BigInteger.TEN).add(nextDigit);
}

Je pense que ce serait bien un peu moins efficace.

Vous pourriez réduire le nombre d'étapes nécessaires en générant neuf chiffres aléatoires à la fois, avec rng.nextInt(1000000000).

Voici les deux versions, on prend un paramètre aléatoire (dans le cas où vous souhaitez réutiliser):

public static BigInteger getRandomNumber(final int digCount){
    return getRandomNumber(digCount, new Random());
}

public static BigInteger getRandomNumber(final int digCount, Random rnd){
    final char[] ch = new char[digCount];
    for(int i = 0; i < digCount; i++){
        ch[i] =
            (char) ('0' + (i == 0 ? rnd.nextInt(9) + 1 : rnd.nextInt(10)));
    }
    return new BigInteger(new String(ch));
}

Le résultat BigInteger aura toujours la longueur spécifiée.

Si n est compris entre 1 à 12 méthode suivante puis aide

private String getRandom(int length) {
    if (length < 1 && length > 12) {
        throw new IllegalArgumentException("Random number generator length should be between 1 to 12");
    }
    long nextLong = Math.abs(random.nextLong());
    return String.valueOf(nextLong).substring(0, length);
}

Une autre chose à noter est qu'il est pas de code bien testé.

Prenez une chaîne avec 5000 chiffres dans le convertir ensuite en BigInteger.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top