简体   繁体   English

如何用Java编写一个输出小于n的完美数字的函数?

[英]How would I write a function in Java that prints out perfect numbers less than n?

I am attempting to write a function in Processing that prints out all perfect numbers less than n for my homework pset. 我试图在处理中编写一个函数,以打印出我的作业pset小于n的所有完美数字。 However, I am having trouble finding an algorithm that matches the problem. 但是,我很难找到与该问题匹配的算法。

I have written a for-loop that cycles through all of the numbers between 1 and n. 我写了一个for循环,循环遍历1到n之间的所有数字。 Since the sum of all of its divisors equals the perfect number, I made an if-statement checking the remainders of n and then adding them onto a sum variable, called "result." 由于所有除数的和等于完美数,因此我进行了if语句,检查n的余数,然后将它们加到求和变量中,称为“结果”。 Then, at the end of this loop, if result equals to n, I printed it out. 然后,在此循环结束时,如果结果等于n,则将其打印出来。

void perfect(int n) {

    int result = 0; 
    for(int i = 1; i < n; i++) {
        if(n % i == 0) {
            result = result + i; 
        }
    }
    if( result == n) {
        println(n); 
    }

}

Currently, my code is not printing out anything. 目前,我的代码没有输出任何内容。 When I removed the if-statement towards the end, it printed out all of the values of n, but not perfect numbers. 当我将if语句移到最后时,它打印出了所有n值,但不是理想数字。 I believe that there is an error somewhere in my code that is making it so that n is never equal to "result." 我相信我的代码中某处正在出错,所以n永远不会等于“结果”。

you will have to use nested for-loop to get all the perfect numbers from 1 to n. 您将必须使用嵌套的for循环来获取从1到n的所有理想数。 As below: 如下:

int i, sum = 1;

System.out.print("Perfect nos from 1 to n are 1,");

for (int j = 2; j <= n; j++)
{
    sum = 1;
    for (i = 2; i < j; i++)
    {
        if (j % i == 0)
            sum = sum + i;
    }
    if (j == sum)
        System.out.print(j + ",");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM