注册 登录
编程论坛 C++教室

[询问][初学者]寻求程序的可改进之处

機器人 发布于 2008-10-23 04:20, 931 次点击
自己正在学习C++程序的, 希望写的程序能够给各位看, 就是想能够得到更多方面的指教。
以下有一段程序, 请问有甚么可以改进的吗? 还是写出来的程序有点乱来...orz

An integer is said to be prime if it is divisible by only 1 and itself. For example,
2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.
a) Write a function that determines whether a number is prime.
b) Use this function in a program that determines and prints all the prime numbers between 2 and 10,000.


#include <iostream>
using std::cout;
using std::endl;

int total=0;

void isPrime (int num) {
  bool prime = true;
  for(int i=2 ; i<=num/2 ; i++) {
    if(num % i == 0) {
      prime = false;
    }
  }
  if(prime) {
    total++;
    cout << num << "\t";
  }
}

int main(void) {
  cout << "The prime numbers from 2 to 10000 are: ";
  cout << endl;

  for(int i=2 ; i<=10000 ; i++) {
    isPrime(i);
  }
  cout << endl;
  cout << "Total of " << total << " prime numbers between 2 and 10000.";

  return 0;
}

[[it] 本帖最后由 機器人 于 2008-10-23 04:26 编辑 [/it]]
4 回复
#2
beyondlwm2008-10-23 09:27
素数?
网上的算法一堆。可以自己搜。
#3
keanbin2008-10-23 14:12
不知道该怎么说?
a) Write a function that determines whether a number is prime.
这句话应该是说,写一个可以判断一个数是否是素数的函数,并没有让你计算素数的总数,而你在
void isPrime (int num)
{
   ......
 if(prime) {
    total++;
    cout << num << "\t";
  }
}
计算了总数,感觉有点画蛇添足,你应该是为了b)着想的吧!不过你有没有想过,如果就单单叫你判断一个数是否是素数,而你却计算有几个素数,这个步骤是不是多余的。我觉得计算素数的步骤可以放到主函数中,而不要放到判断素数的函数中,放到素数的函数中,看起来总感觉很别扭。
#4
lmyouya2008-10-23 14:18
今天你 AC 了吗?
#5
Yummy2008-10-23 16:16
感觉写得好多啊
1