2013-10-30 35 views
1

我写了这两种方法来确定一个数是否完美。我的教授想让我把他们结合起来,看看是否有一个奇数的完美数字。我知道没有一个(这是已知的),但我需要实际编写代码来证明这一点。找到一个奇数的完美数

这个问题与我的主要方法。我测试了两种测试方法。我尝试过调试,它被卡在数字5,但我不明白为什么。这里是我的代码:

public class Lab6 
{ 
public static void main (String[]args) 
{ 
    int testNum = 3; 

    while (testNum != sum_of_divisors(testNum) && testNum%2 != 2) 
    testNum++; 

} 

public static int sum_of_divisors(int numDiv) 
{ 
    int count = 1; 
    int totalDivisors = 0; 

    while (count < numDiv) 
    if (numDiv%count == 0) 
    { 
     totalDivisors = totalDivisors + count; 
     count++; 
    } 
    else 
    count++; 

    return totalDivisors; 
} 

public static boolean is_perfect(int numPerfect) 
{ 
    int count = 1; 
    int totalPerfect = 0; 

    while (totalPerfect < numPerfect) 
    { 
    totalPerfect = totalPerfect + count; 
    count++; 
    } 
    if (numPerfect == totalPerfect) 
    return true; 
    else 
    return false; 
} 
} 
+0

当你说“调试”,你的意思是实际上使用调试器?一个调试器应该告诉你程序卡在哪个方法中。 – chrylis

+1

你在这个代码中没有使用is_perfect –

+0

'testNum%2'是'0'或'1',从不'2'。 – Teepeemm

回答

2

testNum%2 != 2 

testNum%2 != 0 
+0

啊,谢谢。 – coinbird

+0

如果你不介意我问,这个问题如何解决?东西模数2永远不会等于2,那么如何使这个停止在5而不是堆栈溢出? – zgc7009

+0

@ zgc7009,我不确定为什么@CoinBird说它停在'5'。我相信它实际上停在了'6'(第一个完美的数字,虽然不是奇数)。 –

0
testNum=3 
while (testNum != sum_of_divisors(testNum) && testNum%2 != 2) 
    testNum++; 

你可能想要做 'testNum + = 2',因为你所关心的只是奇数和用testNum> 0或其他停止条件替换testNum%2!= 2。最终你的整数会溢出。 “我的教授想让我把他们结合起来,看看是否有一个奇数的完美数字,我知道没有一个(这是已知的),但我需要真正写出代码来证明这一点。”

您的意思是3 & 2^32-1?不知道没有奇怪的完美数字。