檢查親和數對


友元數對或友好數對的概念是不是很有趣?那麼,友元數對究竟是什麼呢?

只有當第一個數的真因數之和等於第二個數的真因數之和時,這兩個數才被稱為友元數對。

另外,以防你忘了,畢達哥拉斯學派總是以公正和友誼等特性將數字聯絡起來。

問題陳述

實現一個程式來檢查給定的數對是否為友元數對。

方法

我們首先考慮給定數對的真因數。將第一個數的真因數相加得到和。同樣,將第二個數的真因數相加得到和。

如果第一個數的真因數之和等於第二個數的真因數之和,我們就稱這對數為友元數對。否則,如果第一個數的真因數之和不等於第二個數的真因數之和,則這對數不是友元數對。

示例輸入輸出

輸入

num1 = 220, num2 = 284

輸出

220 and 280 are amicable pair

解釋

考慮數字 220 和 284。

220 的真因數是 1、2、4、5、10、11、20、22、44、55 和 110。將所有這些因數相加,我們得到和為 284。現在取 284 的真因數。真因數是 1、2、4、71 和 142。將所有這些因數相加,我們得到和為 284。由於我們得到的兩個和相等,我們可以說這對數

220 和 280 是友元數對。

輸入

num1 = 220, num2 = 280

輸出

220 and 280 are not amicable pair

解釋

考慮數字 220 和 280。

220 的真因數是 1、2、4、5、10、11、20、22、44、55 和 110。將所有這些因數相加,我們得到和為 284。現在取 284 的真因數。真因數是 1、2、4、71 和 142。將所有這些因數相加,我們得到和為 284. 280 的真因數為 1, 2, 4, 5, 7, 8, 10, 14, 20, 28, 35, 40, 56, 70, 140。

將所有這些因數相加,我們得到和為 440。由於在這種情況下我們得到的兩個和不相等,我們可以說數對 220 和 280 不是友元數對。

演算法

步驟 1:輸入數字。

步驟 2:找到兩個數字的所有因數之和。

步驟 3:最後檢查一個數字的因數之和是否等於另一個數字。

步驟 4:如果是,則它是友元數,否則不是。

下面是一個 C 程式,用於檢查給定的數對是否為友元數對。

示例

#include<stdio.h>
int main(){
   int i,n1=220,n2=284,DivSum1=0,DivSum2=0;
   //Use one for loop and check for each number starting from 1 to n1 -1.
   for(int i=1;i<n1;i++){
    //Check for each number in the loop if it can divide the number firstNumber or not. If yes, add this number to the DivSum1. After the loop completes, DivSum1 includes the sum of all the divisors for firstNumber.
      if(n1 % i == 0){
         DivSum1 = DivSum1 + i;
      }
   }
   //Same way, determine the sum of all divisors for the second number and save it in DiviSum2.
   for(int i=1;i<n2;i++){
      if(n2 % i == 0){
         DivSum2= DivSum2+ i;
      }
   }
   //Last, check if the sum of divisors of the first number is equal to the second number or not. If it is equal, then print that the numbers are Amicable numbers. Otherwise the numbers are not amicable pairs.
   if((n1== DivSum2) && (n2 == DivSum1)){
      printf("%d and %d are Amicable numbers\n",n1,n2);
   }else{
      printf("%d and %d are not Amicable numbers\n",n1,n2);
   }
}

輸出

執行後,將產生以下輸出

220 and 284 are Amicable numbers.

結論

同樣,我們可以透過輸入任何一對數字來確定給定的數對是否為友元數對。本文解決了確定給定的數對是否為友元數對的挑戰。這裡提供了 C 程式設計程式碼,用於檢查給定的數字是否構成友元數對。

更新於:2023年8月23日

3K+ 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始學習
廣告