Tboy Cá voi
Tổng số bài gửi : 178 Cảm ơn : 413 Danh vọng : 4 Join date : 03/01/2011 Age : 32 Đến từ : TPHCM
| Tiêu đề: Dãy nguyên tố - (Con trỏ) Thu Mar 03, 2011 10:10 pm | |
| | Thu Mar 03, 2011 10:10 pm Dãy nguyên tố - (Con trỏ) | | | - Code:
-
#include <stdio.h> #include <conio.h> #include <math.h> #include <malloc.h> //cap phat mang dong #define Max 100 int *Nhapmang(int N); // Ham tra ve mang 1 chieu int *DayNT(int *A,int N,int *M); //*M la tham bien bool LaNT(int N); void Xuatmang(int *A,int N); void main() { int *a,*b,n,m; //*a,*b y nghia la mang 1 chieu; //m la so phan tu cua mang b,can gia tri cua no thay doi sau khi goi ham DayNT //trong ham DayNT ta cho no la con tro, y nghia la tham bien do { printf("Nhap vao so phan tu n: "); scanf("%d",&n); }while(n<1||n>Max); a=Nhapmang(n);//cho a bang mang ma ham tra ve printf("Cac so vua nhap: "); Xuatmang(a,n); // khi goi ham chi ghi la a, vi *a co y nghia la mang b=DayNT(a,n,&m); printf("\nCac so nguyen to: "); Xuatmang(b,m); getch(); } int *Nhapmang(int N) { int *t; //cap phat mang dong t de ham tra ve t t=(int *)malloc(N*sizeof(int)); /* (int *) la kieu cua mang, tuong ung voi int *t >>Neu cap phat mang 2 chieu thi ghi la int **, tuong tu cho mang n chieu N la so phan tu mang, sizeof(int) la do lon moi phan tu, rieng int la kieu cua moi phan tu Ban chat cua ham malloc la cap phat 1 mang nen khi cap phat mang 2 chieu ta phai cap phat 2 lan */ for(int i=0;i<N;i++) { printf("A[%d]= ",i+1); scanf("%d",&t[i]); } return t; } void Xuatmang(int *A,int N) { for(int i=0;i<N;i++) printf("%d ",A[i]); } int *DayNT(int *A,int N,int *M) { int *t,k=0; *M=0; //tim so phan tu cua mang t, la so so nguyen to trong mang A for(int i=0;i<N;i++) if(A[i]>1&&LaNT(A[i])) (*M)++; // Cap phat dong mang t t=(int *)malloc((*M)*sizeof(int)); for(int j=0;j<N;j++) if(A[j]>1&&LaNT(A[j])) { t[k]=A[j]; k++; } return t; } bool LaNT(int N) { int i=2; while(N%i!=0&&i<=sqrt(N)) i++; if(i<=sqrt(N)) return false; return true; } Tboy
| | | | | |
|