Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรมสำหรับจำนวนคำตอบของสมการโมดูลาร์ใน C/C++


นี่คือปัญหาเชิงสนุกสนานเกี่ยวกับสมการโมดูลาร์ ได้ค่า A และ B ต้องหาจำนวนค่า X ที่เป็นไปได้ ที่ทำให้ (A mod X) = B เป็นจริง

สมมติ A = 26, B = 2 ค่า X ที่ถูกต้องคือ {3, 4, 6, 8, 12, 24} จำนวนคือ 6 นั่นคือคำตอบ

อัลกอริทึม

possibleWayCount(a, b) -

begin
  if a = b, then there are infinite solutions
  if a < b, then there are no solutions
  otherwise div_count := find_div(a, b)
  return div_count
end

find_div(a, b) -

begin
  n := a - b
  div_count := 0
  for i in range 1 to square root of n, do
    if n mod i is 0, then
      if i > b, then
        increase div_count by 1
      end if
      if n / i is not same as i and (n / i) > b, then
        increase div_count by 1
      end if
    end if
  done
end

ตัวอย่างโค้ด C++

#include 
#include 
using namespace std;
int findDivisors(int A, int B) {
    int N = (A - B);
    int div_count = 0;
    for (int i = 1; i <= sqrt(N); i++) {
        if ((N % i) == 0) {
            if (i > B)
                div_count++;
            if ((N / i) != i && (N / i) > B) // ข้ามถ้านับแล้ว
                div_count++;
        }
    }
    return div_count;
}
int possibleWayCount(int A, int B) {
    if (A == B) // ถ้าเท่ากัน มีคำตอบอันนานต
        return -1;
    if (A < B) // ถ้า A < B ไม่มีคำตอบ
        return 0;
    int div_count = 0;
    div_count = findDivisors(A, B);
    return div_count;
}
void possibleWay(int A, int B) {
    int sol = possibleWayCount(A, B);
    if (sol == -1)
        cout << "For A: " << A << " and B: " << B << ", X can take infinite values greater than " << A;
    else
        cout << "For A: " << A << " and B: " << B << ", X can take " << sol << " values";
}
int main() {
    int A = 26, B = 2;
    possibleWay(A, B);
}

ผลลัพธ์

For A: 26 and B: 2, X can take 6 values