# re: 求質(zhì)數(shù)的實(shí)現(xiàn)代碼 回復(fù) 更多評(píng)論
2006-04-24 21:21 by
#include < iostream >
#include <math.h>
using namespace std;
void main() {
int h,g = 0 ;
cout << " 請(qǐng)輸入范圍: " ;
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: 求質(zhì)數(shù)的實(shí)現(xiàn)代碼 回復(fù) 更多評(píng)論
2006-04-25 11:16 by
不用這么復(fù)雜吧。
我覺(jué)得sqrt()不用也沒(méi)什么區(qū)別。
# re: 求質(zhì)數(shù)的實(shí)現(xiàn)代碼 回復(fù) 更多評(píng)論
2006-04-25 21:47 by
除了sqrt可以減少循環(huán)次數(shù)外,質(zhì)數(shù)中除了2是偶數(shù)外,其余質(zhì)數(shù)均為奇數(shù),所以,可以把外邊兩個(gè)for循環(huán)都從=3開(kāi)始,i++和j++改成i+=2和j+=2(能被任何偶數(shù)整除,也能被2整除嘛)...這樣可以省掉更多次計(jì)算
2?直接輸出來(lái)嘛...
# re: 求質(zhì)數(shù)的實(shí)現(xiàn)代碼 回復(fù) 更多評(píng)論
2008-04-27 00:18 by
交個(gè)朋友 我也是寫(xiě)代碼的 現(xiàn)在大二
# re: 求質(zhì)數(shù)的實(shí)現(xiàn)代碼 回復(fù) 更多評(píng)論
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}不是質(zhì)數(shù)", number);
}
else
{
Console.WriteLine("{0}是質(zhì)數(shù)", 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;
}
}
}