我应该使用以下伪代码创建一个完美的数字类:
For i from 2 to “very large”,
For j from 2 to √i,
if (j evenly divides i),
accumulate the sum j and i/j
if √i is an integer
subtract √i ... you added it twice
if the sum of divisors == i
Print the number ... it’s perfect!
所以这是我的版本。它运行,但它根本不做我想要的。它只是运行并且不产生任何输出。有人能告诉我我的程序有什么问题吗?这让我非常困扰。
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
double sum = 0
double newsum = 0;
for (int i = 2; i < 1000000; i++) {
for (int j = 2; i<Math.sqrt(i); j++){
if (i%j==0){
sum = j + (i%j);
}
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a perfect number");
}
}
}
}
}
答案 0 :(得分:1)
您的代码包含多个错误。以下是更正的代码,并对更改进行了评论。
// newsum isn't needed; declare sum to be int to avoid floating-point errors
int sum = 0;
for (int i = 2; i < 1000000; i++) {
// Start with 1; every natural number has 1 as a factor.
sum = 1;
// Test if j, not i, is less than the square root of i.
for (int j = 2; j <= Math.sqrt(i); j++){
if (i % j == 0){
// Add to sum; don't replace sum. Use i / j instead of i % j.
sum = sum + j + (i / j);
// Move test inside this if; test if j is square root of i
if (j*j == i){
// I used j because we know it's the square root already.
sum = sum - j;
}
}
// Move print outside of inner for loop to prevent multiple
// printings of a number.
// Test if sum equals the number being tested, not 0.
if (sum == i) {
// Space before is
System.out.println(sum + " is a perfect number");
}
}
}
输出:
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
答案 1 :(得分:1)
public static void main(String[] args){
int min = 2;
int max = 1000000;
int sum = 0;
for (; min <= max; min++,sum = 0) {
for (int e = 1; e < min; e++)
sum += ((min % e) == 0) ? e : 0;
if (sum == min){
System.out.println(sum);
}
}
}
答案 2 :(得分:0)
这是最简单,最简单的表格,你可以编写一个完美的数字程序....这段代码给出了25的完美数字......你可以随意改变
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)/[^/]+/?$ $1/ [L]
答案 3 :(得分:0)
for(n=1;n<=number;n++){ //calculates the sum of the number.
int i=1;
int sum = 0;
while(i<n){
if(n%i==0)
sum+=i;
i++;
}
if(sum==n){ //if the sum is equal to its sum :
System.out.print(n+": ");
for (int j = 1;j<n;j++){
if(n%j==0){
System.out.print(j+" ");
}
}
System.out.println();
}
}