本文介绍了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 中的质数优化
发布评论