C 素数程序
我想用C语言编写一个程序,它将接受用户输入,而我将无法理解循环的逻辑C 素数程序,c,numbers,C,Numbers,我想用C语言编写一个程序,它将接受用户输入,而我将无法理解循环的逻辑 for ( c = 2 ; c <= n - 1 ; c++ ) for(c=2;cfor循环从c=2到c=n-1,除非它命中了break语句。如果它命中,它将跳出循环。如果你从未中断,那么你的c实际上将在循环后n for ( c = 2 ; c <= n - 1 ; c++ ) 原因如下。循环的工作原理如下: 使用c=2初始化for循环 检查条件(c您认为c最终是n-1的假设是不正确的。如果您使用调试器单步执
for ( c = 2 ; c <= n - 1 ; c++ )
for(c=2;cfor循环从c=2
到c=n-1
,除非它命中了break
语句。如果它命中,它将跳出循环。如果你从未中断,那么你的c
实际上将在循环后n
for ( c = 2 ; c <= n - 1 ; c++ )
原因如下。循环的工作原理如下:
使用c=2初始化for循环
检查条件(c您认为c
最终是n-1
的假设是不正确的。如果您使用调试器单步执行程序,您应该在循环的末尾看到n==11
,c==11
for ( c = 2 ; c <= n - 1 ; c++ )
如果我们没有提前中断,那么循环体最后一次执行的时间确实是c==n-1
但是c
随后增加,循环不变测试在循环c==n
之后失败
如果我将输入11
,那么它将结束于11-1=10
,那么如果(c==n){printf(“%d”,n);
,它将如何放弃的逻辑
现在正确理解for循环条件:
for ( c = 2 ; c <= n - 1 ; c++ )
^^^^^^^^^^^^
2 <= 11 - 1 -> True // {for block executes }
3 <= 11 - 1 -> True // {for block executes }
:
:
9 <= 11 - 1 -> True // {for block executes }
10 <= 11 - 1 -> True // {for block executes }
11 <= 11 - 1 -> False breaks //{And Now for block NOT executes}
if (c == n)
^^^^^^
11 == 11 -> True // {if block executes}
对于n
=11
而言,如果条件计算结果为真且执行了与if相关联的c
=11
同样重要的是要理解,当n
是素数时,for循环只在c=n
终止,但如果假设n
是非素数,则for循环将因c
值小于n-1
而中断,原因是中断;
嵌套if
中的语句会在for循环中阻塞。
for( c = 2; c <= n - 1; c++ )
{
if(n % c == 0)<=="for Non-prime `n`, if condition will be true for some `c < n - 1`"
{ ^^^^^^^^^^^ True
printf("%d is not prime.\n", n);
break; <== "move control outside for-loop"
} // |
} // |
// <---------+ // if break; executes control moves here with c < n - 1
if (c == n)<== "this condition will evaluates FALSE"
^^^^^^^^ False
对于(c=2;c考虑一下当你说一个数字是素数时的意思。
对于每一个n>1,一个数字p是最重要的,请尝试使用调试器查看您在哪里做出了错误的假设。您是在问程序是如何工作的吗?我很困惑,您不是自己编写的吗?请查看堆栈溢出。我如何将此问题转换为堆栈溢出我与此网站不太相似,请指导我。这是我写的算法,不是我写的。事实上,我无法理解c中素数的逻辑。@TayyabGulsherVohra你可以标记它以引起版主的注意,或者当我们得到5个votest时社区将迁移它。这个问题不是很清楚,但在我看来这并不能回答它。你是对的,也是。;)我在重新措辞和解释错误之前回答了这个问题。我希望我的编辑能更好地回答这个问题。@GrijeshChauhan Chauhan thankx buddy我现在能正确理解这个循环。@TayyabGulsherVohra非常好,我很高兴我能帮助你。。祝你好运!:)@TayyabGulsherVohra没问题,Tayyab,正确理解事物总是需要的。好的一点是你对学习的态度。@GrijeshChauhan我想知道一点关于模数符号的知识。如果n=8。for循环将在c=7结束,就像这样,如果(c=2;cWell用完美的例子解释)代替(c=2;c)
int isprime = 1; //use a flag to indicate prime, assume prime until proven otherwise
for ( c = 2 ; //initialize c=2, the first value in the range [2..p-1]
c <= n - 1 ; //check whether c is still in the range [2..p-1]
c++ ) //increment c to the next value in the range [2..p-1]
{
if ( n % c == 0 ) //modulo '%' is the remainder of the integer division
{
isprime = 0;
break;
}
}
printf("%d %s prime.\n", n, isprime?"is":"is not");
for( c = 2; c <= n/2; c++ )