C 中的质数优化

编程入门 行业动态 更新时间:2024-10-24 20:20:43
本文介绍了C 中的质数优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试打印质数;2 到 100 万.但是控制台上没有打印任何内容.你能检查我的代码吗?我怎样才能更优化这段代码?

I try to print the prime numbers; 2 to 1 million. But nothing printed on the console. Could you check my code? And how can I be this code more optimized?

这是我的代码:

#include <stdio.h> #include <math.h> main() { int num, sr, num2; for (num = 2; num <= 1000000; num++) { sr = (int) sqrt(num); for (num2 = 2; sr % num2 != 0; num2++) { if (sr == num2) { printf("%d\n", sr); } } } }

推荐答案

#include <stdio.h> #include <math.h> int main(){ int num, sr, num2; int isPrime = 1; // this is a check parameter; isPrime = 0 if number is not prime. for(num=2; num<=100; num++){ sr = (int) sqrt(num); for(num2=2; num2 <= sr; num2++){ //num2 <== sr to stop the innner loop if(num%num2 == 0){ //printf("=========== %d|%d\n", num,num2); // uncomment this to see if a number is divisable isPrime = 0; // this number is not prime, cos num can be divided by num2 break; } } if(isPrime){ printf("Prime number is %d\n", num); isPrime = 1; // reset the check parameter }else{ isPrime = 1; // reset the check parameter } } return 0; }

此代码有效.既然它有效,我会让你玩它并优化它.如果你不能让我们知道.我们会尽力帮助您.

This code works. Since it works, i'll let you play with it and optimize it. If you can't let us know. We'll try to help you.

我喜欢你使用 sqrt 优化代码的方式.

I like how you used sqrt to optimize the code.

更多推荐

C 中的质数优化

本文发布于:2023-11-29 23:06:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647904.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:质数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!