BigInteger q = new BigInteger(8, 10, new Random());在 Android 中未产生预期结果

发布于 2024-12-20 07:03:18 字数 391 浏览 2 评论 0原文

BigInteger q = new BigInteger(8, 10, new Random()); 每次从桌面运行时都会按预期提供随机数,但在 Android 中则不然。

在Android中我总是只得到相同的输出而不是随机数。请帮我获取随机的 BigIntegr。

供您参考:

int randQ = (int) (Math.random() * 9);      
        for (int r = 0; r < randQ; r++) {

            q = q.nextProbablePrime();
        }

是我所做的快速修复,我对此修复不满意,因为它消耗了额外的时间。 非常感谢您的建议

BigInteger q = new BigInteger(8, 10, new Random()); is giving me random numbers as expected every time while running from my Desktop but not in Android.

in Android I am always getting only same output instead of random number. Please help me to get random BigIntegr.

for your info:

int randQ = (int) (Math.random() * 9);      
        for (int r = 0; r < randQ; r++) {

            q = q.nextProbablePrime();
        }

is the quick fix that I did and I am not happy with this fix since it is consuming extra time.
your suggestions are highly appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寄人书 2024-12-27 07:03:18

这是一个非常常见的问题,与语言或平台无关。

您必须重复使用 Random() 实例才能每次获取随机数。默认构造函数将使用当前时间为伪随机数生成器播种。就您的程序而言,当前时间不会很快变化,因此您会不断获得相同的数字,直到时钟滴答作响。

如果您不重新设定种子,则每次您请求另一个值时,它都会给您不同的数字。您可以通过重用实例并调用来避免重新播种:

Random random = new Random(); // reuse this instance...
int value = random.nextInt(); // use these values instead of new Random()

请参阅:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html

This is a very common problem, independent of language or platform.

You must reuse the instance of Random() to get random numbers each time. The default constructor will seed the pseudo-random number generator with the current time. The current time doesn't change very quickly with respect to your program, so you keep getting the same number until the clock ticks up.

If you don't re-seed, it will give you different numbers each time you ask for another value. You can avoid re-seeding by reusing the instance, and calling:

Random random = new Random(); // reuse this instance...
int value = random.nextInt(); // use these values instead of new Random()

See: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html

滿滿的愛 2024-12-27 07:03:18

已编辑
而是使用:

// creates random object with current instant as seed
Random generator = new Random((new Date()).getTime()); 
BigInteger q = new BigInteger(8, 10, generator);

EDITED
Instead use:

// creates random object with current instant as seed
Random generator = new Random((new Date()).getTime()); 
BigInteger q = new BigInteger(8, 10, generator);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文