C Exercise Example 12

100 Classic C Examples

Title:Determine the prime numbers between 101 and 200.

Program analysis:Method for determining a prime number: divide the number by integers from 2 to sqrt(the number). If it is divisible by any of them, then the number is not prime; otherwise, it is prime.

Example 1

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> int main() { int i,j; int count=0; for (i=101; i<=200; i++) { for (j=2; j<i; j++) { // If j is divisible by i, break out of the loop if (i%j==0) break; } // Check whether the loop breaks early. If j < i, it means i has a divisor between 2 and j. if (j>=i) { count++; printf("%d ",i); // Newline, use count to count, wrap every five numbers if (count % 5 == 0) printf("\n"); } } return 0; }

The output of the above example is:

101 103 107 109 113 
127 131 137 139 149 
151 157 163 167 173 
179 181 191 193 197 
199

Example

#include <stdio.h>
#include <stdbool.h>

// Function: determine whether a number is prime
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;
}

int main() {
    printf("List of prime numbers from 101 to 200:\n");

    for (int i = 101; i <= 200; i++) {
        if (isPrime(i)) {
            printf("%d ", i);
        }
    }

    printf("\n");
    return 0;
}

Code analysis:

  1. isPrimeFunction: Determine whether a number is prime. It first excludes some obvious non-primes, then uses the 6k ± 1 form to check remaining possible factors, thereby improving efficiency.
  2. mainFunction: Traverse all integers between 101 and 200, and useisPrimea function to check whether each number is prime. If it is, print it out.

100 Classic C Examples

other extensions