i have to write a program to find the first N prime numbers, store them in an ar
ID: 3640205 • Letter: I
Question
i have to write a program to find the first N prime numbers, store them in an array and print them out.
We were given the function 'divisible', but i do not know how to call it or make it print the correct numbers.
here is what i have so far:
#include <stdio.h>
#include<ctype.h>
#include <math.h>
typedef enum {false, true} bool;
//test for first 168 prime numbers, and first 12 prime numbers
#define N 10
bool divisible(int [], int );
int main (void)
{
int number=N;
int i, count;
int primes[N];
int flag;
// call divisible function
//print array
getch();
return 0;
}
bool divisible(int primes[], int number)
{
bool flag=true;
int i;
int last;
last = sqrt((double)number);
for(i=0;primes[i]<=last && i < N; i++)
{
if(number%primes[i]==0)
{
flag = true;
break;
}
}
return flag;
}
Explanation / Answer
The divisible() function checks whether a number is prime or not. If the number is prime then it is stored in the array primes[]....:)..
#include <stdio.h>
typedef enum {false, true} bool;
//test for first 168 prime numbers, and first 12 prime numbers
#define N 10
bool divisible(int);
int main ()
{
int i,count=0,p=2;
int primes[N];
for(i=0;i<N;i++)
{
primes[i]=0;
}
bool flag;
// call divisible function
for(i=0;;i++)
{
flag=divisible(p);
if (!flag){ primes[count]=p; count++; }
p++;
if(count==N)break;
}
//print array
for(i=0;i<N;i++)
{
printf("%d ",primes[i]);
}
getch();
return 0;
}
bool divisible(int number)
{
bool flag;
int i,c=0;
for(i=1;i<=number; i++)
{
if(number%i==0) c++;
}
if(c==2) flag=false;
else flag = true;
return flag;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.