java 中switch语句_java – 在switch语句中使用逻辑

我的问题与以下代码有关:

public static void main(String[] args) {

// Find Prime Numbers from 0 to 100

int i;

for (i=2; i <= 100; i++) {

int j = 2;

boolean iPrime = true;

//The following line gives incorrect results, but should execute faster

// while ((iPrime = true) && (j < (i / 2 + 1))) {

//The following line gives correct results but performs un-necessary operations

//by continuing to calculate after the number is found to be "not prime"

while (j < (i / 2 + 1)) {

j++;

if ((i % j) == 0) {

iPrime = false;

//System.out.println(j + " is a factor of " + i);

}

}

if (iPrime) {

System.out.println(i + " is a prime number!");

}

}

}

现在,正如我在代码中所评论的那样,我想要实现的是通过仅在iPrime = true时执行’while’循环来更快地执行我的程序. 50%的数字可被2整除,因此一旦确定,计算就可以停止.

我正在从一本书中做这个项目作为初学者’例子的一部分’,我实际上是想尽可能快地计算高达1000000只是因为我自己的“额外信用”……

我读到了“短路”和“运算符”&&如果前半部分为真,则仅评估语句的后半部分,如果为假,则两者不相互评估(节省CPU)

它也将退出循环,这将节省更多的CPU ……

但由于某种原因,它无法正常工作!我在整个过程中添加了更多的System.out.println()语句,列出了’iPrime’是什么 – 输出是奇怪的……它打开和关闭iPrime并评估每个数字,这是我无法理解的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值