返回列表 發帖

[作業]因數分解 (四) - 兩數求公因數 (由大而小排列)

本帖最後由 陳品肇 於 2021-12-25 10:15 編輯

讓使用者任意輸入兩正整數, 電腦回應它們有那些公因數(由大而小排列), 以及共有幾個公因數.
執行畫面如下:
  1. #include <iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     int count=0;
  7.    int x;
  8.    int y;
  9.    cout<<"請輸入第一個一正整數:";
  10.    cin>>x;
  11.    cout<<"請輸入第二個一正整數:";
  12.    cin>>y;
  13.    cout<<x<<"與"<<y<<"的公因數有:";
  14.    int tmp;
  15.    // x大於y 把y給tmp 否則 把x給tmp
  16.    tmp = x>y ? y : x;
  17.    
  18.    for(int i=tmp;i>=1;i--)
  19.    {
  20.        // 當i可以被 x 與 y整除,那它就是公因數
  21.        if(x%i==0 && y%i==0)
  22.        {
  23.           cout<<i<<" ";
  24.           count++;
  25.        }
  26.    }
  27.    cout<<endl;
  28.    
  29.     cout<<"總共有"<<count<<"個"<<endl;
  30.     system("pause");
  31.     return 0;   
  32. }
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊

返回列表