改進兩點,
一.用根號縮小判斷範圍
二.用+2取代+1減少要判斷的數
公告版位
星落的瞬間!放棄的後悔是永遠!
- Aug 15 Fri 2008 01:03
質因數判斷加強版,感謝某網友提供想法
/*
Name: 質因數判斷加強版,感謝某網友提供想法
Date: 19/06/08 09:59
*/
#include <iostream>
#include <cmath>
int main()
{
using namespace std;
double Num2;
unsigned long Num,bh,x;
char a;
bool temp;
again:
cout << "請輸入一個正整數:__________\b\b\b\b\b\b\b\b\b\b";
cin >> Num;
Num2 = sqrt(Num);
temp = true;
if (Num == 2)
goto exit;
if (Num % 2 == 0 or Num <2){
temp = false;
goto exit;
}
for (unsigned long i = 3;i <= Num2;i = i + 2){
if (Num % i == 0){
temp = false;
goto exit;
}
}
exit:
if (temp == false)
cout << "\n不是質數。\n";
else
cout << "\n是質數。\n";
cout << "是否繼續?(y/n)";
cin.get();
a = getchar();
system("cls");
if (a == 'y')
goto again;
else
//system("pause");
return 0;
}
全站熱搜
留言列表