dimanche 1 mars 2015

Prime numbers in C and is_prime



I'm writing a program to find all of the prime numbers contained within a user input n. I am having trouble with the is_prime function.



#include <stdio.h>
#include <math.h>

main() {
int n;
int k;

// gets user input for length of string
// and stores it as n
printf("Enter the value of n:");
scanf("%d", &n);

for (k = 2; k <= n; k++) {
if (is_Prime(k) == 1) {
printf("Printing primes less than or equal to %d: /n %d, &n, &k");
}
}


I want the output to look like this, but I am not sure how to print the list without using different variables for each prime number.



Printing primes less than or equal to 30:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29.


//here is the is_Prime function
is_Prime (int n)
{
for(j = 2; j <= n/2; j++)
{
if(n%j != 0)
{
return 1;
break;
}
}
if(n%j == 0 )
return 0;
}


I am not sure how to call the is_prime subroutine? Any help?




Aucun commentaire:

Enregistrer un commentaire