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

Refactorable Number (ตัวเลขที่หารตัวประกอบของตัวเองลงตัว) ใน C++

เราได้รับค่าประเภทจำนวนเต็ม ให้เรียกว่า number งานคือตรวจสอบว่าตัวเลขที่กำหนดเป็น Refactorable Number หรือไม่ หากใช่ ให้พิมพ์ว่าเป็น Refactorable Number มิฉะนั้น พิมพ์ว่าไม่เป็นไปได้

Refactorable Number คืออะไร?

ตัวเลขจะเป็น Refactorable เมื่อมันหารด้วยจำนวนตัวประกอบ (Factors) ทั้งหมดของมันลงตัว ตัวอย่างเช่น ตัวเลข 9 เป็น Refactorable เพราะมีตัวประกอบทั้งหมด 3 ตัว (1, 3, 9) และ 9 หาร 3 ลงตัว ดังนั้นมันจึงเป็น Refactorable Number

ดูสถานการณ์ Input-Output ต่างๆ

Input - int number = 9

Output - It is a Refactorable number

คำอธิบาย - ตัวเลขเป็น Refactorable เมื่อมันหารด้วยจำนวนตัวประกอบทั้งหมดลงตัว เราได้รับตัวเลข 9 ซึ่งเป็น Refactorable เพราะมีตัวประกอบทั้งหมด 3 ตัว (1, 3, 9) และ 9 หาร 3 ลงตัว

Input - int number = 10

Output - It isn't a Refactorable number

คำอธิบาย - ตัวเลขเป็น Refactorable เมื่อมันหารด้วยจำนวนตัวประกอบทั้งหมดลงตัว เราได้รับตัวเลข 10 ซึ่งไม่ใช่ Refactorable เพราะมีตัวประกอบทั้งหมด 4 ตัว (1, 2, 5, 10) และ 10 ไม่หาร 4 ลงตัว ดังนั้นมันไม่ใช่ Refactorable Number

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

  • รับตัวแปรประเภทจำนวนเต็ม ให้เรียกว่า number

  • ส่งข้อมูลไปยังฟังก์ชัน check_Refactorable(int number) แบบ bool

  • ภายในฟังก์ชัน check_Refactorable(int number)

    • ประกาศตัวแปรจำนวนเต็มเป็น count = 0

    • เริ่มลูป FOR จาก i=1 ถึง i น้อยกว่าหรือเท่ากับ sqrt(number) ภายในลูป ตรวจสอบ IF number % i == 0 แล้วตรวจสอบ IF number / i == i แล้วเพิ่ม count ขึ้น 1 (Pre-increment)

    • ELSE ตั้งค่า count = count + 2

    • คืนค่า number % count == 0

  • พิมพ์ผลลัพธ์

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

#include <bits/stdc++.h>
using namespace std;

bool check_Refactorable(int number) {
    int count = 0;
    for (int i = 1; i <= sqrt(number); ++i) {
        if(number % i == 0) {
            if(number / i == i) {
                ++count;
            } else {
                count += 2;
            }
        }
    }
    return number % count == 0;
}

int main() {
    int number = 9;
    if(check_Refactorable(number) == 1) {
        cout<<"It is a Refactorable number";
    } else {
        cout<<"It isn't a Refactorable number";
    }
    return 0;
}

ผลลัพธ์

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

It is a Refactorable number