我想打印从2到100的素数。但代码中有一些错误。谁有人指出? [英] I want to print prime numbers from 2 to 100. But some error is there in the code. Can anyone point out ?

查看:86
本文介绍了我想打印从2到100的素数。但代码中有一些错误。谁有人指出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int i, j, count =0;

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

    {
        if (i % j == 0)
        {
            count++;

        }
    }

    if (count == 2)
    {
        Console.WriteLine("This is a prime number" + i);
        count = 0;
    }

}

Console.ReadLine();

推荐答案

如果当前计数为2,您只能重置计数,但是您应该始终重置它。



您只需要检查您正在检查的数字的平方根。



并查看< a href =http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes> http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes [ ^ ]
You only reset count if the current count is two, but you should always reset it.

And you only need to check up to the square root of the number you are checking.

And look into http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes[^]


int i, j, count =0;

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

     {
         if (i % j == 0)
         {
             count++;
         }
     }

     if (count == 2)
     {
         Console.WriteLine("This is a prime number" + i);
     }

     // This should be after the if, as we need to make it 0 every time.
     count = 0;
 }

 Console.ReadLine();



1.你应该有第二个循环条件,如 j< = i 而不是 j< = 100

实际上你需要检查这个数字是否可以被1,2除尽......直到你要比较的数字(那就是i)。



2.每次计数应该为0,但是当它处于素数时,你会在if条件下使它为0。

所以,2,3是素数,当4来时它不会计数0,因此停止。





谢谢......


1. You should have the second loop condition like j<=i and not j<=100.
Actually you need to check whether the number is divisible with 1, 2.... upto the number you are comparing with (that is i).

2. Count should be 0 every time, but you are making it 0 when it is prime, inside the if condition.
So, 2, 3 are prime, and when 4 comes it does not make count 0, hence stops.


Thanks...


这篇关于我想打印从2到100的素数。但代码中有一些错误。谁有人指出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆