求解一道C语言题目
设计子函数:int GetPrime(int a[],int b[],int n) 展开
2020-04-12
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int GetPrime(int a[], int b[], int n) {
int C = 0;
for(int i = 0; i < n; i++) {
int j;
if(a[i] == 1 || a[i] % 2 == 0)
continue;
for(j = 2; j * j <= a[i]; j++)
if(a[i] % j == 0)
break;
if(j * j > a[i])
b[C++] = a[i];
}
return C;
}
int main() {
int a[20], b[20], n;
srand(time(NULL));
for(int i = 0; i < 20; i++)
a[i] = rand() % 99 + 1;
n = GetPrime(a, b, 20);
printf("原始数组:\n");
for(int i = 0; i < 20; i++)
printf("%d%c", a[i], i % 5 == 4 ? '\n' : ' ');
if(n == 0)
printf("\nNO");
else {
printf("\n素数数组:\n");
for(int i = 0; i < n; i++)
printf("%d%c", b[i], i % 5 == 4 ? '\n' : ' ');
}
putchar('\n');
return 0;
}
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int GetPrime(int a[],int b[],int n)
{
int i,cnt,t;
for(i=0,cnt=0;i<n;++i)
{
if(a[i]<2)continue;
for(t=2;t<a[i];t++)
if(a[i]%t==0)
break;
if(t==a[i])
b[cnt++]=a[i];
}
return cnt;
}
int main()
{
int i,a[20],b[20],t;
srand(time(NULL));
for(i=0;i<20;++i)
{
a[i]=rand()%99+1;
printf("%2d%c",a[i],(i+1)%5==0?'\n':' ');
}
for(i=0,t=GetPrime(a,b,sizeof(a)/sizeof(a[0]));i<t;++i)
printf("%d ",b[i]);
printf("%s",t==0?"NO":"\n");
return 0;
}