2015年1月16日 星期五

P1 選修C 的三個Prime程式

除了以下這三個之外還有兩個範例,明日(1/17)會加入
第一個prime-1.cpp 輸入一個數 n 判斷是否為質數
#include <iostream>
using namespace std;
int main()
{
  int n , i ;
 
  while( cin >> n )
  {
    if(n==1) { cout << "No\n"; continue; }
    for(i=2; i<n; ++i)
      if( n % i == 0 )  break;

    if( i <n ) cout << "No";
    else       cout << "Yes";
    cout << endl;
  }        
  system("pause");
  return 0;
}

第二個prime-2.cpp 輸入一個數 n 判斷是否為質數
#include <iostream>
#include <cmath>  // sqrt
using namespace std;
bool isp( int n )   // 函數方式判斷是否質數
{
  int q = int(sqrt(n));   // 只須檢查至平方根
  int i;  
  if(n==1)  return false;
  for(i=2; i<=q; ++i)
      if( n % i == 0 )  return false;
  return true;  
}
   
int main()
{
  int n ;
  while( cin >> n )
  {
    if( isp(n) ) cout << "Yes\n";
    else       cout << "No\n";
  }        
  system("pause");
  return 0;

}

第三個prime-3.cpp 輸入一個數 n  列出1~n的質數,每10個換列
#include <iostream>
#include <cmath>  // sqrt
using namespace std;
bool isp( int n )
{
  int q = int(sqrt(n));
  int i;  
  if(n==1)  return false;
  for(i=2; i<=q; ++i)
      if( n % i == 0 )  return false;  
  return true;  
}    
int main()
{
  int i,n,cnt ;
  while( cin >> n )
  {
     cnt =0;
     for(i=2; i<=n; ++i)
       if( isp(i) )
       {
          cout << i << " ";
          if((++cnt)%10==0) cout << endl;
       }
  cout << endl;                
  }        
  system("pause");
  return 0;
}


0 意見:

張貼留言