#7871: 請問一直出現TLE,如何調整Coding?


zs10130884 (123)


 

請問一直出現TLE,請指教下列程式如何調整Coding? 感謝!

#include <iostream>
#include <math.h>
using namespace std;
int main(){
  int n,j,flag;            //flag為旗標變數,flag等於1時,表示為質數,flag等於0時,表示為非質數
  float rt;
    while (cin >> n){
    flag=1;
    j=2;
    rt=sqrt(n);
    while (j<=rt){
      if ((n%j)==0) {
        flag=0;
        break; 
      }
      j++;  
    }      
    if (flag){
      cout << "質數" << endl;   
    } else {
      cout << "非質數" << endl;      
    }  
  }
}