[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
定义:素数一般指质数。质数是指在大于1的自然数中,除1和它本身以外不在有其他因数的自然数。
那么怎么通过代码的方式来判断1~100中的素数并打印出来呢?
思路1:通过素数的定义,假设我们取数字m,用m去除2~m-1的所有整数,若每次相除余数都为0,那么m肯定就是素数了。
代码实现:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> int main() { int i = 0; for
(int m = 2; m <= 100; m++) //遍历1~100所有数 { for (i = 2; i <= m - 1;
i++)//遍历2~m-1中的数 { if (m % i == 0) { break; //说明2~m-1中存在一个数能被m整除,则此m不是素数 } }
//跳在这情况有两个,(1.因上面break终止循环,不是素数 2.break未发生,是素数)所以我们要用if判断 if (i > (m - 1))
//如果是素数的话,i值肯定大于m-1 { printf("%d ", m);//打印素数 } } return 0; }
运行结果:
思路2:还可以运用一个数学思想,假设取数字m,那就是我们可以用m去除2~sqrt(m)之间的所有整数,若都不能被m整除,那么m就是素数。这是一个数学原理。
注:sqrt()是一个数学函数,表示开平方,要引头文件<math.h>
代码实现:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<math.h> int main()
{ int i = 0; for (int m = 2; m <= 100; m++) //遍历1~100所有数 { for (i = 2; i <=
sqrt(m); i++) //2~根号m的所有数 { if (m % i == 0) { break; //如果2~根号m的所有数能被m整除,则不是素数 }
} if (i > sqrt(m)) //判断若i大于根号m,则m是素数 { printf("%d ", m); //打印素数 } } return 0; }
运行结果:
思路3:我们知道除2以外素数肯定是奇数,我们取数字2~200之间的一个数字m,用m去除3~m之间的所有奇数,若都不能被整除,那么m肯定是素数。
代码实现:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<math.h> int main()
{ int i = 0; for (int m = 3; m <= 200; m+=2) { for (i = 3; i < m; i += 2) { if
(m % i == 0) { break; } } if (i == m) { printf("%d ", m); } } return 0; }
运行结果:
判断素数的方法有很多,上面是我推荐的三种简易方法判断素数,希望能帮助大家!