Board logo

標題: 因數分解 (四) - 求公因數 [打印本頁]

作者: may    時間: 2023-5-9 18:37     標題: 因數分解 (四) - 求公因數

讓使用者任意輸入兩正整數, 電腦回應它們有那些公因數, 以及共有幾個公因數.
執行畫面如下:

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {  
  6.     re:
  7.     int x, y, smaller, sum=0;
  8.     cout<<"請輸入第一個數: ";
  9.     cin>>x;
  10.     cout<<"請輸入第二個數: ";
  11.     cin>>y;
  12.     smaller=x<y?x:y;
  13.     cout<<x<<"與"<<y<<"的公因數有: ";
  14.     for(int i=1; i<=smaller; i++)
  15.     {
  16.         if(x%i==0 && y%i==0)
  17.         {
  18.             cout<<i<<" ";
  19.             sum++;
  20.         }
  21.     }
  22.     cout<<endl<<"共有"<<sum<<"個!"<<endl<<endl;
  23.     goto re;
  24.     return 0;   
  25. }
複製代碼





歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://seed.istak.org.tw/) Powered by Discuz! 7.2