【问题标题】:Java: Produce larger random numbersJava:产生更大的随机数
【发布时间】:2014-04-29 22:47:09
【问题描述】:

为了好玩,我在 java 中创建了一个简单的素数分解程序。现在我正在使用 Random 类和 nextLong() 方法为“temp”分配一个随机数,范围在 quintillions 中,并以惊人的速度对其进行分解。我应该使用什么数据类型或算法或方法来获得更大的值?

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;   
   }}
        }
   }}}

【问题讨论】:

  • 如果你使用量子计算机仍然无法得到最大的随机数
  • 它很快就会考虑到它,因为它是错误的。我不确定你知道你在这段代码中做什么。 if(temp%ii == 0) 然后... ii = temp +1 为什么?例如,对于数字 81,您会得到什么输出?你得到“3 3 3 3”吗?
  • BigInteger 浮现在脑海中......
  • 我不明白这个问题,没有“最大随机数”。你的意思是最大的可以装双吗?还是计算机可以代表的最大还是.....? (BigInterger 仅具有基于可用内存的大小限制)
  • 尝试使用输入 81 peter 运行它,它会工作。我在几秒钟内分解了 5684275247958 之类的数字,然后将主要因素重新相乘,然后它就起作用了。

标签: java random int long-integer factorization


【解决方案1】:

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

BigInteger(int numBits, Random rnd)

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

【讨论】:

    【解决方案2】:

    这是无用的,可悲的是编码。您可以玩大数字并说它很快,但重点不是“我的数字有多大”……而是“因素有多大”。只需取一个大素数并休眠,直到您的代码正常工作。

    对于大数生成...有 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 1970-01-01
      • 2019-04-13
      • 2019-12-15
      相关资源
      最近更新 更多