ในส่วนนี้ เราจะมาดูกันว่าเราจะหาตัวประกอบเฉพาะของตัวเลขอย่างมีประสิทธิภาพได้อย่างไร มีตัวเลขบอกว่า n =1092 เราต้องหาตัวประกอบเฉพาะของตัวนี้ให้ได้ ตัวประกอบเฉพาะของ 1092 คือ 2, 2, 3, 7, 13 เพื่อแก้ปัญหานี้ เราต้องปฏิบัติตามกฎนี้ -
-
เมื่อตัวเลขหารด้วย 2 ลงตัว ให้พิมพ์ 2 แล้วหารจำนวนด้วย 2 ซ้ำๆ
-
ตอนนี้ตัวเลขต้องเป็นเลขคี่ ตอนนี้เริ่มจาก 3 ถึงรากที่สองของตัวเลข หากตัวเลขหารด้วยค่าปัจจุบันได้ลงตัว ให้พิมพ์และเปลี่ยนตัวเลขโดยหารด้วยตัวเลขปัจจุบันแล้วดำเนินการต่อ
มาดูอัลกอรึทึมกันดีกว่าครับ
อัลกอริทึม
printPrimeFactors(n)
begin while n is divisible by 2, do print 2 n := n / 2 done for i := 3 to √𝑛, increase i by 2, do while n is divisible by i, do print i n := n / i done done if n > 2, then print n end if end
ตัวอย่าง
#include<stdio.h>
#include<math.h>
void primeFactors(int n) {
int i;
while(n % 2 == 0) {
printf("%d, ", 2);
n = n/2; //reduce n by dividing this by 2
}
for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers
while(n % i == 0) {
printf("%d, ", i);
n = n/i;
}
}
if(n > 2) {
printf("%d, ", n);
}
}
main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
primeFactors(n);
} ผลลัพธ์
Enter a number: 24024 2, 2, 2, 3, 7, 11, 13,