【发布时间】: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