2014年5月24日 星期六

應用

由N個數所組成的數中,求最大的質數
範例
p.in
2
2 3
p.out
2 2 22 0 
3 2 32 0 
2 3 23 1 
3 3 33 0 
max:23

#include <iostream>
#include <cmath>
using namespace std;
int N,M; //#balls, #draw
bool IsPrime(int num)
{
 if(num<=1)
  return false;
 for(int i=2; i<=sqrt(num*1.0); i++)
 {
  if(num%i==0)
   return false;
 }
 return true;
}
 
int main () { 
 int *A,*B;
 int max=0;
 cin >> N;
 A=new int[N];
 B=new int[N];
 for (int i=0;i<N;i++) cin >>A[i];
 int size=(int)pow((float)N,(float)N);
 for (int i=0;i<size;i++){
  int a=i;
 
  for (int j=0;j<N;j++){
   B[j]=A[a%N];
   a = a/N;
  } 
  for (int j=0;j<N;j++){
   cout << B[j] << ' ';   
  } 
  int b=0;
  for (int j=0;j<N;j++){
   b = b*10+B[j];   
  } 
  cout << b << ' ';
  bool p =IsPrime(b); 
  cout << p << ' ';
  if (p&&b>max) max=b;
  cout << endl;
 }
 cout << "max:" << max << endl;
}

沒有留言:

張貼留言