C语言 C 语言中 1 到 100 之间的质数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41444655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prime numbers between 1 to 100 in C Programming Language
提问by user7369637
I want to print prime numbers between 1 to 100, I write my code like the following but when I run it, it starts printing 3,7,11,17....91 Why not the code print 2? Please help me friends
我想打印 1 到 100 之间的质数,我编写如下代码,但是当我运行它时,它开始打印 3,7,11,17....91 为什么代码不打印 2?请朋友帮帮我
#include <stdio.h>
int main(void)
{
for(int i=2;i<100;i++)
{
for(int j=2;j<i;j++)
{
if(i%j==0)
break;
else if(i==j+1)
printf("%d\n",i);
}
}
}
回答by Klas Lindb?ck
The condition i==j+1will not be true for i==2. This can be fixed by a couple of changes to the inner loop:
对于 ,条件i==j+1将不成立i==2。这可以通过对内部循环进行一些更改来解决:
#include <stdio.h>
int main(void)
{
for (int i=2; i<100; i++)
{
for (int j=2; j<=i; j++) // Changed upper bound
{
if (i == j) // Changed condition and reversed order of if:s
printf("%d\n",i);
else if (i%j == 0)
break;
}
}
}
回答by Raghi Pandit
#include <stdio.h>
int main () {
int i, j;
for(i = 2; i<100; i++) {
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime", i);
}
return 0;
}
回答by suraj
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
回答by Zarrar Niazi
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j;
int b=0;
for (i=2;i<=100;i++){
for (j=2;j<=i;j++){
if (i%j==0){
break;
}
}
if (i==j)
print f("\n%d",j);
}
getch ();
}
回答by Huort UP
#include<stdio.h>
main()
{
int i,j,k;
for(i=2;i<=100;i++)
{
k=0;
for(j=2;j<=i;j++)
{
if(i%j==0)
k++;
}
if(k==1)
printf("%d\t",i);
}
}

