如何在 C 语言中检查素数
什么是素数?
素数是指除自身和 1 之外,不能被其他正整数整除的自然数。
C 语言中检查素数的方法
1. 暴力算法
- 遍历从 2 到 待检测数的平方根的所有整数。
- 如果待检测数能被遍历的整数整除,则它不是素数。
- 如果待检测数无法被任何遍历的整数整除,则它是一个素数。
代码实现:
#include <stdio.h> #include <math.h> int is_prime(int num) { if (num <p><strong>2. 费马小定理</strong></p> <ul><li>对于任何素数 p 和任何整数 a,a^(p-1) % p = 1。</li></ul> <p><strong>代码实现:</strong></p> <pre class="brush:php;toolbar:false">#include <stdio.h> int is_prime(int num) { if (num <p><strong>3. Miller-Rabin 算法</strong></p> <ul><li>这是检查素数的一种更有效的算法,但实现起来比较复杂。</li></ul> <p><strong>代码实现:</strong></p> <pre class="brush:php;toolbar:false">#include <stdio.h> #include <stdlib.h> #include <stdint.h> int is_prime(int num) { if (num </stdint.h></stdlib.h></stdio.h>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。