親密數

親密數是這樣的:A的所有因子之和等於B ,B的所有因子之和也等於A。那麼這兩個數互爲親密數。

要求:A,B不能相同。

static void Main(string[] args)
       {
           for (int i = 1 ; i < 3000; i++)
           {
               Program p=new Program ();
               int j = p.GetFamilyNumber(i);
               if (j!=-1)
               {
                   Console.WriteLine("{0}和{1}是親密數",i,j);
               }
           }
       }
       /// <summary>
       /// 得到一個數的所有因子之和
       /// </summary>
       /// <param name="x"></param>
       /// <returns></returns>
       public int GetFactors(int x)
       {
           int temp = 0;
           for (int i = 1; i < x; i++)
           {
               if (x%i==0)
               {
                   temp += i;
               }
           }
           return temp;
       }
       //得到一個數的親密數
       public int GetFamilyNumber(int x)
       {
           int temp1 = GetFactors(x);//A的所有因子之和等於B
           int temp2 = GetFactors(temp1);//B的所有因子之和等於C
           if (x==temp2 &&temp1>temp2)//如果A=C,那麼AB是親密數,兩個數不能相同前面算過的後面不能再算了
           {
               return temp1;
           }
           return -1;
       }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章