在 C++ 中計算滿足 A % X = B 的所有 X 的可能值個數


給定兩個整數 A 和 B 以及一個數字 X。目標是找到 X 的可能值個數,使得 A%X=B。如果 A==B,則 X 有無限多個可能值,因此返回 -1。如果 A < B,則沒有解,因此返回 0。如果 A>B,則返回 (A-B) 的約數個數作為結果。

例如

輸入

A=5, B=2

輸出

Count of all possible values of X such that A % X = B are: 1

解釋

5%3=2. So X is 3 here.

輸入

A=10, B=10

輸出

Count of all possible values of X such that A % X = B are: −1

解釋

Here A==B so there are infinite solutions so −1 is returned.

以下程式中使用的演算法如下

在這種方法中,我們將使用 for 迴圈從 i=1 到 i*i<=(A−B) 計算 (A-B) 的約數。如果任何 i 完全整除 (A-B),則相應地更新計數。

  • 輸入整數 A 和 B。

  • 如果 A<B,則列印 0 作為結果。

  • 如果 A==B,則列印 -1 作為結果。

  • 對於 A>B,函式 possible_values(int A, int B) 獲取 A 和 B 並返回滿足 A % X = B 的所有 X 的可能值個數。

  • 將初始計數設定為 0,X=A−B。

  • 使用 for 迴圈從 i=1 到 i*i<(A−B) 遍歷,以計算 X 的約數。

  • 如果任何 i 完全整除 X,則令 temp=i,temp_2=B−1,如果 i*i!=X,則設定 temp_2 = X / i。

  • 如果 temp>B 且 temp_2 >B,則遞增計數。

  • 在迴圈結束時,返回計數作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int possible_values(int A, int B){
   int count = 0;
   int X = A − B;
   for (int i = 1; i * i <= A − B; i++){
      if(X % i == 0){
         int temp = i;
         int temp_2 = B − 1;
         if(i * i != X){
            temp_2 = X / i;
         }
         if(temp > B){
            count++;
         }
         if(temp_2 > B){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int A = 15, B = 5;
   if(A < B){
      cout<<"Count of all possible values of X such that A % X = B are: "<<0;
   }
   else if(A == B){
      cout<<"Count of all possible values of X such that A % X = B are: "<<−1;
   }
   else{
      cout<<"Count of all possible values of X such that A % X = B are: "<<possible_values(A, B);
   }
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

Count of all possible values of X such that A % X = B are: 1

更新於:2021年1月5日

174 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.