Tìm số nguyên tố thứ k trong mảng .

on Friday, January 2, 2015
Tìm số nguyên tố thứ k trong mảng .
Ví dụ : 2 3 4 5 6
Nhập k=2 thì xuất ra 3

#include 
#include 
#include 
#define MAX 100

// Khai báo nguyên mẫu hàm.
void NhapMang(int[], int);
void XuatMang(int[], int);
bool KiemTraSoNguyenTo(int);


void NhapMang(int a[], int n)
{
 for (int i = 0; i < n; i++)
 {
  printf("\nNhap vao a[%d] = ", i);
  scanf("%d", &a[i]);
 }
}

void XuatMang(int a[], int n)
{
 for (int i = 0; i < n; i++)
 {
  printf("%4d", a[i]);
 }
}

bool KiemTraSoNguyenTo(int x)
{
 if (x < 2)
 {
  return false;
 }
 else if (x > 2)
 {
  if (x % 2 == 0)
  {
   return false;
  }
  for (int i = 3; i <= sqrt((float)x); i += 2)
  {
   if (x % i == 0)
   {
    return false;
   }
  }
 }
 return true;
}


bool TimSoNtoThuk(int a[], int n, int k, int *res){
 int i, pos = 0, temp = a[0];
 if (k<0 || k>n)
  return false;
 for (i = 0; i<n; i++){
  if (KiemTraSoNguyenTo(a[i])==true ){
   temp = a[i];
   pos++;
  }
  if (pos == k){
   *res = temp;
   return true;
  }
 }
 return false;
}


int main()
{
 int a[MAX], n,k;

 // Nhập vào số lượng phần tử của mảng.
 do{
  printf("\nNhap vao so luong phan tu cua mang: ");
  scanf("%d", &n);

  if (n < 0 || n > MAX)
  {
   printf("\nSo luong phan tu khong hop le. Xin kiem tra lai !");
  }
 } while (n < 0 || n > MAX);

 NhapMang(a, n);
 XuatMang(a, n);

 printf("Nhap vao k");
 scanf("%d", &k);
 int res;
 if (TimSoNtoThuk(a, n, k, &res)==false){
  printf("Khong tim thay so nguyen to thu %d \n", k);

 }
 else printf("\nSo nguyen to thu %d la  %d", k, res);

 getch();
 return 0;
}

0 comments:

Post a Comment