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

โปรแกรม C++ แสดงตัวประกอบของจำนวน (Factors of a Number)


ตัวประกอบ (Factors) คือ ตัวเลขที่คูณกันแล้วได้ตัวเลขเป้าหมาย

ตัวอย่าง: ตัวประกอบของ 15 คือ 1, 3, 5, 15 เพราะ 1×15=15 และ 3×5=15

วิธีที่ 1: เขียนใน main โดยตรง

#include <iostream>
using namespace std;

int main() {
    int num = 20, i;
    cout << "The factors of " << num << " are: ";
    for (i = 1; i <= num; i++) {
        if (num % i == 0)
            cout << i << " ";
    }
    return 0;
}

ผลลัพธ์

The factors of 20 are: 1 2 4 5 10 20

วิธีที่ 2: ใช้ Function แยก

#include <iostream>
using namespace std;

void factors(int num) {
    for (int i = 1; i <= num; i++) {
        if (num % i == 0)
            cout << i << " ";
    }
}

int main() {
    int num = 25;
    cout << "The factors of " << num << " are: ";
    factors(num);
    return 0;
}

ผลลัพธ์

The factors of 25 are: 1 5 25

ทั้งสองวิธีใช้ลูป for วนจาก 1 ถึง num ตรวจสอบว่า num % i == 0 หรือไม่ ถ้าใช่แสดงว่า i เป็นตัวประกอบ