# re: 求質數的實現代碼 回復 更多評論
2006-04-24 21:21 by
#include < iostream >
#include <math.h>
using namespace std;
void main() {
int h,g = 0 ;
cout << " 請輸入范圍: " ;
cin >> g;
for ( int i = 2 ;i <= g;i ++ ) {
h = 1 ;
for ( int j = 2 ;j <= sqrt( i);j ++ )
{
if ((i % j == 0 ) && (j != i)) {
h = 0 ;
break ;
}
}
if (h)
cout << i << endl;
}
}
# re: 求質數的實現代碼 回復 更多評論
2006-04-25 11:16 by
不用這么復雜吧。
我覺得sqrt()不用也沒什么區別。
# re: 求質數的實現代碼 回復 更多評論
2006-04-25 21:47 by
除了sqrt可以減少循環次數外,質數中除了2是偶數外,其余質數均為奇數,所以,可以把外邊兩個for循環都從=3開始,i++和j++改成i+=2和j+=2(能被任何偶數整除,也能被2整除嘛)...這樣可以省掉更多次計算
2?直接輸出來嘛...
# re: 求質數的實現代碼 回復 更多評論
2010-05-05 14:30 by
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ZhiShu
{
class Program
{
static void Main(string[] args)
{
for (int number = 2; number < 1000; number++)
{
if(IsZhiShu(number))
{
Console.WriteLine("{0}不是質數", number);
}
else
{
Console.WriteLine("{0}是質數", number);
}
}
}
public static bool IsZhiShu(int Num)
{
int counter = 0;
for (int i = 1; i < Num; i++)
{
int total = Num % i;
if (total == 0)
{
counter++;
}
}
if (counter > 1)
return true;
else
return false;
}
}
}