改進兩點,
一.用根號縮小判斷範圍
二.用+2取代+1減少要判斷的數

/* 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; }

arrow
arrow
    全站熱搜

    讓地獄深紅的天亮 發表在 痞客邦 留言(0) 人氣()