2015-11-03 107 views
1

正如所描述的標題,我想創建一個函數,告訴我兩個數字我給的是友好的,但由於某種原因,我得到了錯誤的答案,我希望有人會看到這個問題。友好的數字函數給出了錯誤的結果

public class Amicable{ 

public static void main(String[] args){ 

    int n, m; 
    int ndivisorsSum = 0; 
    int mdivisorsSum = 0; 

    n = Integer.parseInt(args[0]); 
    m = Integer.parseInt(args[1]); 

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

    for(int i = 1; i < m; i++){ 
     if (m % i == 0){ 
      mdivisorsSum = mdivisorsSum + i; 
     } 
    } 

    if (ndivisorsSum == mdivisorsSum) { 
     System.out.println(n + " and " + m + " are amicable numbers"); 
    }else{ 
     System.out.println(n + " and " + m + " are not amicable numbers"); 
    } 

} 
} 

回答

5

引用維基百科:

親和數是如此相關,使得每個的適當的除數的總和等於所述其他號碼兩個不同的數字。 (除了數字本身之外,數字的恰當除數是該數字的正數因子,例如,6的適當除數是1,2和3.)一對友好數字構成了第2期的等分序列。一個相關的概念是一個完美數字,它是一個等於它自己的合適除數之和的數字,換句話說就是一個形成周期1等分序列的數字。數字是週期大於等於一個等分序列的成員2被稱爲社交數字。

所以最終失敗的是你的條件,檢查兩個數字是否友好。你需要檢查n的所有divies的總和是否等於m和vica verse。

int n, m; 
int ndivisorsSum = 0; 
int mdivisorsSum = 0; 

n = 220; 
m = 284; 

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

for(int i = 1; i < m; i++){ 
    if (m % i == 0){ 
     mdivisorsSum += i; 
    } 
} 

if (ndivisorsSum == m && mdivisorsSum == n) { // Your mistake is here. 
    System.out.println(n + " and " + m + " are amicable numbers"); 
}else{ 
    System.out.println(n + " and " + m + " are not amicable numbers"); 
} 
1

這不是amicable數字的定義(根據維基百科)。

應該

if (nDivisorsSum == m && mDivisorsSum == n) 

您也應該檢查這些數字是不同的,正被輸入時。您可以使用一個do-while循環重複,直到給出有效的輸入。

相關問題