PART B · PRESCRIBED EXERCISE 04

Generate the first n prime numbers

Understand the algorithm. Run the code.
Explain the result with confidence.

Read the programOpen the playground
Aim & definitionStep-by-step algorithmWorked sampleExtra test cases3 viva answers

LAB B04 · 01

Understand the task.

Aim: Generate the first n prime numbers.

DEFINITION

Prime number. A prime number is an integer greater than one with no positive divisors other than one and itself.

Review the related theory in Unit 4.

LAB B04 · 02

Know what goes in and what comes out.

One count n from 1 to 100. Generate the first n primes, rather than all primes less than or equal to n.

Sample input

5

Expected output

First 5 primes: 2 3 5 7 11

Source programs read the documented input directly, without prompt text, so the same sample works in the embedded compiler’s STDIN field.

LAB B04 · 03

Plan the steps before writing code.

  1. Read and validate the requested count. Start candidate at 2 and count at zero.
  2. Use isPrime to test the candidate.
  3. If prime, print it and increment count.
  4. Advance candidate and repeat until count equals n.
  5. Finish the output line.

LAB B04 · 04

One complete program. Ready to run.

Generate the first n prime numbersmain.c
#include <stdio.h>
int isPrime(int number);
int main(void)
{
    int n, count = 0, candidate = 2;
    if (scanf("%d", &n) != 1 || n < 1 || n > 100) {
        puts("Enter a prime count from 1 to 100."); return 1;
    }
    printf("First %d primes:", n);
    while (count < n) {
        if (isPrime(candidate)) { printf(" %d", candidate); count++; }
        candidate++;
    }
    putchar('\n');
    return 0;
}
int isPrime(int number)
{
    int divisor;
    if (number < 2) return 0;
    for (divisor = 2; divisor <= number / divisor; divisor++) {
        if (number % divisor == 0) return 0;
    }
    return 1;
}
EXPECTED OUTPUTFirst 5 primes: 2 3 5 7 11

Try this programDownload B04-first-n-primes.c
Compile on your own computer
gcc B04-first-n-primes.c -o program

Run the generated program and enter the sample input. The examples use standard C90-compatible syntax and explicit function declarations. For these learning programs, enter numeric values representable in the stated C types and within the documented ranges.

LAB B04 · 05

Connect each statement to its purpose.

  • 1 is not prime, so the search starts at 2.
  • isPrime checks possible divisors only while divisor <= number / divisor, equivalent to divisor² <= number for positive values.
  • The division form avoids overflowing a divisor * divisor expression for larger extensions of the program.
  • The smallest divisor found proves the candidate composite; otherwise the function returns 1.
  • The loop terminates after n successful prime tests, not after checking n candidates.

LAB B04 · 06

Follow the sample calculation.

Step or componentWhat happens
2, 3Prime → count reaches 2.
4Divisible by 2 → skip.
5Prime → count 3.
6, then 7Skip composite 6; accept prime 7 → count 4.
8, 9, 10, then 11Skip three composites; accept 11 → count 5. Result: 2 3 5 7 11.

LAB B04 · 07

Check more than one input.

Try this input or caseExpected behaviour
1First 1 primes: 2
102 3 5 7 11 13 17 19 23 29
100Exactly 100 primes; final value 541.

Time and storage

If p_n is the nth prime, the straightforward trial-division search uses at most O(p_n × sqrt(p_n)) time and O(1) extra working space.

Start with the sample, then test a boundary and a case that changes the result. A correct sample alone does not establish that every input is handled correctly.

LAB B04 · 08

Use the real C compiler.

Choose an example and load it into the embedded C compiler. Select I/O inside the compiler, check the sample STDIN, and press Run. Change the input or edit the source to explore a different case.

Sample input (STDIN)

5

Expected output

First 5 primes: 2 3 5 7 11

Load the compiler when you’re ready to practise.

Your C workspace

Edit real C code and see real compiler output.

Compiler provided by OneCompiler. Opening the editor connects to that service; code and input you run are processed there. If the embed is unavailable, open the C compiler in a new tab and paste the source below.

View / copy the selected source
#include <stdio.h>
int isPrime(int number);
int main(void)
{
    int n, count = 0, candidate = 2;
    if (scanf("%d", &n) != 1 || n < 1 || n > 100) {
        puts("Enter a prime count from 1 to 100."); return 1;
    }
    printf("First %d primes:", n);
    while (count < n) {
        if (isPrime(candidate)) { printf(" %d", candidate); count++; }
        candidate++;
    }
    putchar('\n');
    return 0;
}
int isPrime(int number)
{
    int divisor;
    if (number < 2) return 0;
    for (divisor = 2; divisor <= number / divisor; divisor++) {
        if (number % divisor == 0) return 0;
    }
    return 1;
}

LAB B04 · 09

Explain why the program works.

Why test only up to the square root?

A composite number has a factor pair; at least one factor is no greater than its square root.

Is 2 prime?

Yes. It has only divisors 1 and 2 and is the only even prime.

What is the difference between first n primes and primes up to n?

For n = 5, the first five are 2, 3, 5, 7, 11, while primes up to five are only 2, 3, 5.

LAB B04 · 10

Build the next skill.

Read the viva answers, try the extra cases, and return to the lab index to mark this exercise as practised.