这段代码做了什么

时间:2015-01-22 14:09:30

标签: java for-loop int counter

有人可以解释这段代码到底是什么以及它在做什么吗?谢谢!

for (int i = 2; i <= max; i++) {
    counter = 0;
    for (int n = 2; n < i; n++) {
        if (i % n == 0) {
            counter++;
        }
    }
    if (counter == 0) {
        System.out.println(i);
    }
}

2 个答案:

答案 0 :(得分:0)

打印2到最大的素数

它的工作原理如下:

start with i as 2 and step by one every time
check with every element less than i (so if i is 5, check with 2,3,4) that divide by number i and if it is increment the counter.
if counter is 0, print that number

答案 1 :(得分:-1)

+program to generate prime number between 2 and MAX
but the time complexity is more, u can reduce it by
for(i=2;i<=MAX;i++)
{
  count=0;
   for(n=2;n<=i/2;n++)
   { 
     if(i%n==0)
      {
        count=1;
        break;
      }
  }
  if(count==0)
     Sop(i);    
}