Code a C program to find how many prime numbers are there between n and m. Asking the user and makign the appropriate input sanitizations and error handling.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a C program to find the number of prime numbers between n and m with input validation and error handling:
c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#define MAX_INPUT 100
#define MAX_RANGE 1000000
bool isPrime(int num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 == 0 || num % 3 == 0) return false;
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0)
return false;
}
return true;
}
bool validateInput(char *input, int *value) {
// Check if input is empty
if (strlen(input) == 0) return false;
// Check if input contains only digits
for (int i = 0; input[i] != '\0'; i++) {
if (input[i] == '\n') input[i] = '\0';
if (!isdigit(input[i]) && input[i] != '\0') return false;
}
// Convert to integer
*value = atoi(input);
// Check range
if (*value < 0 || *value > MAX_RANGE) return false;
return true;
}
int countPrimes(int n, int m) {
int count = 0;
for (int i = n; i <= m; i++) {
if (isPrime(i)) count++;
}
return count;
}
int main() {
char input[MAX_INPUT];
int n, m;
// Get and validate n
while (1) {
printf("Enter the lower bound (n): ");
if (fgets(input, MAX_INPUT, stdin) == NULL) {
printf("Error reading input. Please try again.\n");
continue;
}
if (validateInput(input, &n)) break;
printf("Invalid input. Please enter a positive integer between 0 and %d.\n", MAX_RANGE);
}
// Get and validate m
while (1) {
printf("Enter the upper bound (m): ");
if (fgets(input, MAX_INPUT, stdin) == NULL) {
printf("Error reading input. Please try again.\n");
continue;
}
if (validateInput(input, &m)) {
if (m >= n) break;
printf("Upper bound must be greater than or equal to lower bound (%d).\n", n);
} else {
printf("Invalid input. Please enter a positive integer between 0 and %d.\n", MAX_RANGE);
}
}
printf("Counting prime numbers between %d and %d...\n", n, m);
int result = countPrimes(n, m);
printf("There are %d prime numbers between %d and %d.\n", result, n, m);
return 0;
}
Would you like me to explain or break down this code?