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

นับค่า X ที่ทำให้ A % X = B ด้วย C++

ได้รับจำนวนเต็ม A และ B และตัวเลข X เป้าหมายคือหาจำนวนค่าที่ X สามารถเป็นได้ ที่ทำให้ A % X = B สำหรับสมการนี้ ถ้า A == B แล้ว X จะมีค่าได้ไม่จำกัด คืนค่า -1 ถ้า A < B ไม่มีคำตอบ คืนค่า 0 ถ้า A > B คืนค่าจำนวนตัวหารของ (A-B)

ตัวอย่าง

Input

A=5, B=2

Output

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

Explanation

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

Input

A=10, B=10

Output

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

Explanation

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

วิธีการที่ใช้ในโปรแกรม

วิธีนี้คำนวณตัวหารของ (A-B) โดยใช้ลูป for จาก i=1 ถึง i*i <= (A-B) ถ้า i หาร (A-B) ลงตัว ให้อัปเดตจำนวนนับตามนั้น

  • รับจำนวนเต็ม A และ B เป็นอินพุต
  • ถ้า A < B พิมพ์ 0 เป็นผลลัพธ์
  • ถ้า A == B พิมพ์ -1 เป็นผลลัพธ์
  • สำหรับ A > B ฟังก์ชัน possible_values(int A, int B) รับ A และ B คืนค่าจำนวน X ที่เป็นไปได้
  • กำหนดจำนวนนับเริ่มต้นเป็น 0 และ X = A - B
  • วนลูปจาก 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 ให้เพิ่มจำนวนนับ
  • เมื่อลูปสิ้นสุด คืนค่า count เป็นผลลัพธ์

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

#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;
}

Output

หากรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

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