Skip to content

Instantly share code, notes, and snippets.

@edymanoloiu
Created June 11, 2012 10:30
Show Gist options
  • Save edymanoloiu/2909477 to your computer and use it in GitHub Desktop.
Save edymanoloiu/2909477 to your computer and use it in GitHub Desktop.
find prime numbers in a vector
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int prim (int n)
{
int i,aux=sqrt(n);
for(i=2; i<=aux; i++)
if(n%i==0)
return 0;
return 1;
}
int main(){
int nr,i,*x;
printf("nr=");
scanf("%d",&nr);
x=(int *)malloc(nr*sizeof(int));
for(i=1; i<=nr; i++)
{
printf("x[%d]=",i);
scanf("%d",&x[i]);
}
for(i=1; i<=nr; i++)
if(prim(x[i]))
printf("%d este prim\n",x[i]);
return 0;
}
@vladfulgeanu
Copy link

At line 6 is better optimized if you use: for(i = 2; i <= sqrt(n); i++).
sqrt() function requires <math.h> to be included.
Also use spaces between operators for example instead of "i<=nr" use "i <= nr".

@ZNickq
Copy link

ZNickq commented Jun 11, 2012

@FULLVLAD Agree, but using sqrt(n) that way is bad too! It will cause the method to be called on every check, causing overhead...it's better to store the sqrt in another variable and check against that!

@edymanoloiu
Copy link
Author

Am facut schimbarile propuse.

@vladfulgeanu
Copy link

@ZNickq I agree. Forgot that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment