C / C ++中的素数 [英] Prime number in C/C++
本文介绍了C / C ++中的素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的疑问,我的一个朋友将这段代码传给我,该函数正在查找所提供的号码是否为素数。
问题是我不明白为什么代码工作,得到它?我无法理解算法背后的逻辑。
这是代码:http://www.mediafire.com/view/?c2o477ach484kbd
感谢您的帮助。
Here is my doubt , a friend of mine pass me this code, that the function is finding if the provided number is prime or not .
The problem is that I do not understand why the code works,get it? I can not understand the logic behind the algorithm.
Here is the code :http://www.mediafire.com/view/?c2o477ach484kbd
Thanks for any help .
int main(void)
{
int n, c = 2;
printf("enter the value:");
scanf("%d",&n);
for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n%c == 0 )
{
printf("not a prime number");
break;
}
}
if ( c == n )
printf("prime number");
system("PAUSE");
return 0;
}
推荐答案
嗯,这不是最有效的方式,但是,这样的代码是正确的:如果数字是素数然后它的整数除以较小的数字产生(非零)提醒。你朋友的代码利用了这样的属性。
Well, that''s not the most efficient way, but yes, such code is correct: if a number is prime then then its integer division by a smaller number produces a (non-zero) reminder. Your friend''s code exploits such property.
你可以阅读这个,它可能会有所帮助:
查找素数 [ ^ ]
You could read this, it might be helpful:
Finding prime numbers[^]
这篇关于C / C ++中的素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文