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

โปรแกรม C แสดงจำนวนเฉพาะระหว่างสองช่วง


ป้อนตัวเลข 2 จำนวนที่คอนโซลระหว่างรันโปรแกรม จากนั้นประกาศตัวแปรแฟล็ก (flag) ใช้ตรวจสอบว่าตัวเลขเป็นจำนวนเฉพาะหรือไม่ ด้วยเงื่อนไขลูป for

เมื่อแฟล็กเป็นศูนย์ จะพิมพ์จำนวนเฉพาะ และถ้าแฟล็กเป็น 1 จะออกจากลูป

โปรแกรม

โปรแกรม C แสดงจำนวนเฉพาะระหว่างสองช่วง:

#include <stdio.h>

int main() {
    int number1, number2, i, j, flag;
    
    printf("enter the two intervals:");
    scanf("%d %d", &number1, &number2);
    
    printf("prime no's present in between %d and %d:", number1, number2);
    
    for(i = number1 + 1; i < number2; i++) { // ช่วงระหว่างสองตัวเลข
        flag = 0;
        for(j = 2; j <= i / 2; ++j) { // ตรวจสอบจำนวนเฉพาะ
            if(i % j == 0) {
                flag = 1;
                break;
            }
        }
        if(flag == 0)
            printf("%d\n", i);
    }
    return 0;
}

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

enter the two intervals: 10 50
the number of prime numbers present in between 10 and 50:
11 13 17 19 23 29 31 37 41 43 47

พิจารณาอีกตัวอย่างหนึ่ง ที่เราพยายามนำจำนวนเฉพาะออกจากระหว่างสองตัวเลข

ตัวอย่าง

โปรแกรม C แสดงตัวเลขระหว่างสองช่วง โดยไม่นับจำนวนเฉพาะ:

#include <stdio.h>

int main() {
    int number1, number2, i, j, flag;
    
    printf("enter the two intervals:");
    scanf("%d %d", &number1, &number2);
    
    printf("the numbers that are present after removing prime numbers in between %d and %d:\n", number1, number2);
    
    for(i = number1 + 1; i < number2; i++) { // ช่วงระหว่างสองตัวเลข
        flag = 1;
        for(j = 2; j <= i / 2; ++j) { // ตรวจสอบจำนวนเฉพาะ
            if(i % j == 0) {
                flag = 0;
                break;
            }
        }
        if(flag == 0)
            printf("%d\n", i);
    }
    return 0;
}

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

enter the two intervals: 10 20
the numbers that are present after removing prime numbers in between 10 and 20:
12 14 15 16 18