-3

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?

user56521
  • 31
  • 2
  • 6

2 Answers2

1
printf("Printing primes less than or equal to %d:\n", n);
for(k = 2; k <= n; k++)
{
    if(is_Prime(k) == 1)
    {
        printf("%d, ", k);
    }
}
wyas
  • 377
  • 2
  • 14
0
printf("Printing primes less than or equal to %d:\n%s", n, (n >= 2 ? "2" : ""));

for (k = 3; k <= n; ++k)
  if (is_Prime(k))
    printf(", %d", k);

printf("%s\n", (n >= 2 ? "." : ""));

Here's a slightly cleaner version of your is_Prime function:

int is_Prime(int n)
{
  if (n < 2)
    return 0;

  int last = (int) sqrt(n) + 1;  /* conservatively safe */

  for (int j = 2; j <= last; ++j)
    if (0 == n % j)
      return 0;

  return 1;
}

Note that you only really need to check up to the sqrt() of a number to find all its potential factors.

Also note that this is not a great way to find all the primes less than n, which is the prime purpose of your program, especially when you will repeatedly call this function incrementing n by 1 each time. I recommend trying to implement the Sieve of Eratosthenes or the Sieve of Sundaram instead -- so long as n isn't too large.

jschultz410
  • 2,849
  • 14
  • 22