[{"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}]
求100以内的所有素数并输出。
(素数:一个大于1的整数,除了1和它本身外,不能被其他整数整除)
难度指数:★★★
方法:双重循环
解题思路分析:
1.使用外部for循环获取2-100所有整数
(因为素数是一个大于1的整数,所以从2开始)
2.使用内部for循环获取2-number本身的所有整数
(因为除了1和它本身外,不能被其他整数整除,所以获取2到它本身的所有整数)。
3.(重点)在内部for循环内使用if选择结构,判断除数number能否被被除数i整除。
number % i == 0
情况一: 除数number被被除数i除本身以外的数整除,break跳出内部for循环。
情况二: 除数number被被除数i自身整除,break跳出内部for循环。
4.(重点)在外部for循环内使用if选择结构,判断除数number与被除数i是否相等。
情况一:如果相等,输出i,(number是素数)
情况二:如果不相等,不输出i,(number是素数)
注意:
1.number是局部变量,只在外部for循环内有效,可以在表达式以中声明变量
2.i不能在内部for循环表达式中声明变量,
如果在内部for循环表达式中声明变量,则i是内部for循环中的局部变量,只在内部for循环有效。
就无法参与外部for循环内的if选择结构
3.i变量应声明全局变量,或在外部for循环内声明局部变量。
代码如下
package cn.work.home; public class Text02 { public static void main(String[]
args) { int i; //使用外部for循环获取2-100所有整数 for(int number = 2; number <= 100;
number++ ) { //使用内部for循环获取2-number本身的所有整数 for( i = 2; i <= number; i++ ) {
//在内部for循环内使用if选择结构,判断除数number能否被被除数i整除。 if( number % i == 0 ) { break; } }
//在外部for循环内使用if选择结构,判断除数number与被除数i是否相等。如果相等,则输出素数。 if( i == number ) {
System.out.println(number); } } } }
运行结果如下