查找特定的正整数 [英] Finding specific positive integer

查看:85
本文介绍了查找特定的正整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到整数n,以便当1/z + 1/x = 1/n时有1000种组合.这是我的代码:

I want to find the integer, n, so that there are 1000 combinations when 1/z + 1/x = 1/n. This is my code:

int counter = 0;
    double n = 1;

    while (true) {
        for (double i = 1; i < 10000; i++) {
            for (double t = 1; t < 10000; t++) {
                if ((1/i) + (1/t) == (1/n)) {                       
                    counter++;
                    System.out.println(counter);
                }
            }           
        }   
        if (counter < 1000) {
            counter = 0;
            n++;
        } else {
            System.out.println("Counterr: " + counter);
            System.out.println("Answer: " + n);
            System.exit(0);
        } 
    } 

如果我尝试找到4个组合,它会起作用,但是当我找到1000个组合时,它不会起作用.为什么?

It works if I try to find 4 combinations, but not when 1000. Why?

推荐答案

这可能是因为浮点精度问题.您可以在循环内的double上使用增量 ++ 运算符,并按 == 比较双精度数.这些操作的结果可能与预期不符,尤其是经过多次迭代之后.

That's probably because of floating point precision issues. You use increment ++ operator on double within a loop and compare doubles by ==. Result of those operations may be not as expected, especially after many iterations.

尝试更改您的代码以使用具有精确精度的整数,而不是双精度数.请注意,您的方程式

Try changing your code to work with integers with exact precision, not doubles. Note that your equation

1/z + 1/x = 1/n

1/z + 1/x = 1/n

等同于

n *(x + z)= x * z

n * (x + z) = x * z

因此,如下更改循环:

    for (int i = 1; i < 10000; i++) {
        for (int t = 1; t < 10000; t++) {
            if (n * (i + t) == i * t) {
                counter++;
                System.out.println(counter);
            }
        }           
    }

此外,现在还有更清晰的方法来优化迭代范围.考虑 i t 的上限和下限-减少迭代范围将显着提高整体性能.

Also, there is now more clear how to optimize your iteration ranges. Think about lower and upper limits for i and t - reducing iteration ranges will improve overall performance significantly.

不幸的是,我暂时还没有测试结果,但是我很确定您应该以整数而不是双精度进行计算.

Unfortunately, I didn't tested the result at the moment, but I'm pretty sure you should do calculations in integers, not in doubles.

这篇关于查找特定的正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆