素数
Learning Goals
- Practice using
forloops - Using modulo
- Creating a Boolean function

背景
素数 numbers are defined as whole numbers greater than 1, whose only factors are 1 and itself. So 3 is 素数 because its only factors are 1 and 3, while 4 is composite and not 素数, because it is the product of 2 × 2. In this 实验 you will 编写一个n algorithm to generate all 素数 numbers in a range specified by the user.
- 提示
- Modulo 五月 come in handy, as it produces the remainder when dividing two integers.
- By definition, 1 is not a 素数 number.
- There is only one even 素数 number, 2.
演示

入门
- Log into cs50.dev using your GitHub account.
- Click inside the terminal window and execute
cd. - At the
$prompt, typemkdir prime - Now execute
cd prime - Then copy and paste
wget https://cdn.cs50.net/2022/fall/实验s/1/prime.cinto your terminal to 下载 this 实验’s 分发代码. - You are to complete the Boolean function,
prime, which tests if a number is 素数, and returns true if it is, and false if it is not.
实现细节
The easiest way to check if a number is 素数, is to try dividing it by every number from 2 up to, but not including, the number itself. If any number divides into it with no remainder, that number is not 素数.
The main function in the 分发代码 contains a for loop that iterates through the range specified by the user, with both ends inclusive. 例如, if the user types in 1 for min and 100 for max, the for loop will test each number, 1 to 100. Each of these numbers is passed to a function, prime, that you will implement to return either true or false depending on whether the number is 素数.
Thought 问题
- Can you make the 素数-finding algorithm 更多 efficient than checking if a number is divisible by every number between 2 and 1 较少 than itself? Can you think of another way to generate 素数 numbers?
如何测试 Your Code
你的程序应该 behave per the例子below.
prime/ $ ./prime
Minimum: 1
Maximum: 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
You can check your code using check50, a program that CS50 will use to test your code when you 提交, by typing in the following at the $ prompt. But be sure to test it自己 as well!
check50 cs50/实验s/2023/x/prime
Green smilies 意思 your program has passed a test! Red frownies will indicate your program output something unexpected. Visit the URL that check50 outputs to see the input check50 handed to your program, what output it expected, and what output your program actually gave.
To evaluate that the style of your code (indentations and spacing) is correct, type in the following at the $ prompt.
style50 prime.c
如何提交
No need to 提交! This is an 可选 练习题.