Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to generate 20 digits random number in Java

2 Answers

0 votes
import java.math.BigDecimal;
import java.util.Random;

public class Generate20DigitsRandomNumber_Java {
    static BigDecimal generate20DigitsRandomNumber() {
        Random rand = new Random();
        StringBuilder s = new StringBuilder();

        for (int i = 0; i < 20; i++) {
            s.append(rand.nextInt(9) + 1);
        }

        BigDecimal dec;
        try {
            dec = new BigDecimal(s.toString());
        } catch (NumberFormatException e) {
            System.out.println("exception: " + e);  
            return BigDecimal.valueOf(-1);
        }

        return dec;
    }

    public static void main(String[] args) {
        System.out.println(generate20DigitsRandomNumber());
    }
}


 
/*
run:

92557329183678384369
 
*/

 



answered Nov 9, 2024 by avibootz
0 votes
import java.math.BigInteger;
import java.security.SecureRandom;

public class Generate20DigitsRandomNumber_Java {
    public static void main(String[] args) {
        SecureRandom random = new SecureRandom();
        
        // Generate a random number with 20 digits by taking the modulo the random number 
        // with 10^20,  it ensures that the result is a number between 0 and 99999999999999999999
        
        // bitLength = 130 = number will have approximately 39 decimal digits
        
        // new BigInteger("10").pow(20) = 100000000000000000000
        
        BigInteger randomNumber = new BigInteger(130, random).mod(new BigInteger("10").pow(20));
        
        System.out.println(randomNumber);
    }
}

 
/*
run:

83959522836397842242
 
*/

 



answered Nov 9, 2024 by avibootz

Related questions

1 answer 78 views
1 answer 67 views
1 answer 95 views
1 answer 85 views
1 answer 93 views
1 answer 85 views
1 answer 96 views
...