Java:产生更大的随机数

时间:2014-04-29 22:47:09

标签: java random int long-integer factorization

我在java中创建了一个简单的素数分解程序,以获得它的乐趣。现在我使用Random类和nextLong()方法来分配" temp"随机数在五分之一和因子中惊人地快速。我应该使用什么数据类型或算法或方法来获得更大的值?

import java.util.Random;
import javax.swing.JOptionPane;

public class factor {
public static void main(String[] args) {
   Random gen = new Random();
   String factors = "";
   long temp = 0;
   String hello = JOptionPane.showInputDialog("Type a random number(Must be smaller than 4,611,686,018,427,387,904), or type 1 for a random large number.");
  temp = Long.parseLong(hello);
   if(temp < 2)
   temp = Math.abs(gen.nextLong());
   long temp2 = temp;
   System.out.println("  The factors of   \n\n  " + temp2 + "   are:");
   System.out.println("");
   while(temp != 1){
       //System.out.print(temp);
   for(long ii = 2; ii <= (Math.ceil(Math.sqrt(temp))); ii++){
  // if(ii%12345 == 0)
 // System.out.println(temp + " " + ii + " " + factors);
        if(temp%ii == 0){
            factors = factors + "  " + ii;
           // System.out.println(temp + " " + ii + " " + factors);
            temp = temp/ii;
            ii = temp + 1;       
  }else{
   if(ii == Math.ceil(Math.sqrt(temp))){
   factors = factors + " " + temp;
            System.out.println(factors);
            temp = 1;
            ii = temp + 1;   
   }}
        }
   }}}

2 个答案:

答案 0 :(得分:4)

您可以使用BigInteger的随机构造函数:

BigInteger(int numBits, Random rnd)

如果您需要更多信息,可以查看API:BigInteger

答案 1 :(得分:0)

它没用,而且编码很糟糕。你可以玩大号并说它很快但重点不是“我的数字有多大”......这是“因素有多大”。只需拿一个大素数并睡觉,直到你的代码工作。

对于大数代......有BigInteger

public class Factor {

    public static BigInteger generateBigOne() {
        final Random random = new Random();

        long loop = random.nextLong();
        String result = "";
        for (int i = 0; i < loop; i++) {
            result += random.nextLong();
        }
        return new BigInteger(result);
    }
}