Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

Write a C program that identifies prime numbers within a user-defined range [a, b],…

  1. User

    Write a C program that identifies prime numbers within a user-defined range [a, b], where both 'a' and 'b' are inputs provided by the user.

  2. Assistant
    #include <stdio.h>
    #include <stdbool.h>
    
    // Function to check if a number is prime 
    bool isPrime(int number) {
        // Handle edge cases
        if (number <= 1) return false;
        if (number <= 3) return true;
    
        // This is checked so that we can skip middle five numbers in below loop
        if (number % 2 == 0 || number % 3 == 0) return false;
    
        for (int i = 5; i * i <= number; i += 6) {
            if (number % i == 0 || number % (i + 2) == 0)
                return false;
        }
        return true;
    }
    
    int main() {
        int a, b;
    
        // Ask user for the range [a, b]
        printf("Please enter the range [a, b] to find prime numbers:\n");
        printf("Enter a: ");
        scanf("%d", &a);
        printf("Enter b: ");
        scanf("%d", &b);
    
        // Checking and correcting if the user inputs the range in reverse order
        if (a > b) {
            int temp = a;
            a = b;
            b = temp;
        }
    
        printf("Prime numbers in the range [%d, %d] are:\n", a, b);
    
        for (int i = a; i <= b; i++) {
            if (isPrime(i)) {
                printf("%d ", i);
            }
        }
        printf("\n");
    
        return 0;
    }
    

    This program consists of a main function and a utility function named isPrime. The isPrime function determines whether a given number is prime. The program prompts the user to input a range [a, b]. It then checks each number within this range and prints out those that are prime. The algorithm handles edge cases and uses a slightly optimized check to reduce the number of iterations needed to determine if a number is prime, especially useful for larger numbers.