在简单的素数代码中需要帮助 [英] need help in simple prime number code

查看:55
本文介绍了在简单的素数代码中需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int n;
            bool prime = true;
            Console.Read();
            for(int i=2;i<n-1;i++)>
            {
                if((n/i)==0)
                {prime=false;
                }
                break;}
            if(prime==true){
            Console.WriteLine("Yes the no. is prime");}
            else{
            Console.WriteLine("NO this is not prime");
            }
            }


    }
}


我希望每当我写素数时都向我显示消息,但是我在此代码中遇到的问题是对的还是不对.我该如何实现.


i want that whenever i write a prime number it show me message but i am getting problem in this code is right or not.how can i implement.

推荐答案

您的代码将确定整数是否是质数,但是效率不是很高,如果要测试的质数很小,这可能无关紧要.

如果您意识到N = Sqrt(N)* Sqrt(N),则可以轻松优化代码,这意味着您的循环条件将为i< = sqrt(n)
虽然这可以优化您的代码,但是当您要测试大整数时,它仍然不是一个好的解决方案.我知道,确定整数是否为质数的最佳算法是 Miller-Rabin检验 [ ^ ]


我只是看到您的代码实际上是不正确的.
您将需要初始化n课程.并且您说n/i == 0表示n不是质数,那是不正确的.如果n%i == 0,则n不是质数.您也可以在if块之外休息,这样您的循环将在第一次运行后停止.
Your code will determine if a integer is a prime number or not, but not very efficiently, which might not matter if the prime numbers you''re going to test are small.

You can easely optimize your code if you realize that N = Sqrt(N)*Sqrt(N) which means your loop condition would be i<=sqrt(n)
While this optimizes your code it''s still not a good solution when you''re gonna test big integers. The best algorithm, I know of, for determining whether an integer is a prime or not is the Miller-Rabin test[^]


I just saw that your code actually isn''t correct.
you''ll need to initialize n ofcourse. and you''re saying that n/i == 0 means that n is not a prime, that is not correct. If n%i == 0 then n is not a prime. You also have your break outside your if-block so your loop will stop after the first run through.


这篇关于在简单的素数代码中需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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