c - 在通过键盘输入 n 时打印从 1 到 n 的素数
问题描述
我知道我的代码有点奇怪,但我刚开始编码,有人可以帮我弄清楚为什么我的代码不起作用
int n,i,j;
printf("enter the value\n");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
for(j=2;j<=i;j++)
{
if( (i%j==0) && (i!=j) )
{
break;
}
else if(i!=j)
{
continue;
}
}
if(i==j)
{
printf("prime no are %d\n",i);
continue;
}
}
解决方案
该程序不记录数字何时为质数。尝试 :
int n,i,j,prime_count;
bool is_prime;
printf("enter the value\n");
scanf("%d",&n);
prime_count = 0;
for(i=2;i<=n;i++)
{
is_prime = true;
for(j=2;j<i;j++)
{
if( (i%j) == 0 )
{
is_prime = false;
break;
}
// As said by Achal you may not need this condition,
// Your loop will continue by itself
// else if(i!=j)
// {
// continue;
// }
}
if(is_prime)
{
prime_count++;
}
}
// Then you can do what you want with the number of primes found
// e.g. print it :
printf("Number of primes: %d\n", prime_count);
推荐阅读
- ios - 在 WKWebView 中点击按钮后 UIButton 选择器不起作用
- emacs - 带有emacs org-mode的Haskell:变量不在范围内
- python - 按分位数对 Pandas 数据帧进行排名
- r - 在 R Studio 中自定义制图输出的困难
- c++ - 带有嵌套模板参数的 std::vector
- sharepoint - 如何在基于 SharePoint 的流中修复“拒绝访问 - 错误 403”
- tensorflow - 使用 macOS 安装 tfjs-node 时失败,并且 node-gyp 重建失败
- reactjs - React - 操作 DOM 还是使用状态?
- android - 离子时间选择无法显示 Android 的 AM / PM
- python - 如何在使用 plotly 进行子图绘制时隐藏 x 轴值