Search code examples
cloopsprimespointer-arithmeticfunction-definition

Print prime numbers using pointer arithmetic


My function writePrime has to write all prime numbers from array using pointer arithmetic. I cannot use any other function except main and writePrime.

#include <stdio.h>
void writePrime(int arr[], int n) {
  int *q = arr, *qq = arr, i, prime;
  while (q < arr + n) {
    while (qq < arr + n) {
      i = 1;
      if (*qq % i != 0)
        continue;
      else
        prime = 1;
      i++;
      qq++;
    }
    if (prime == 1)
      printf("%d ", *q);
    q++;
  }
}
int main() {
  int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 92, 93, 94, 95, 96};
  int n = sizeof(arr) / sizeof(*arr);
  writePrime(arr, n);
  return 0;
}

This code just prints the same unchanged array. How could I modify this to work?


Solution

  • The variable n should be declared as having the type size_t

    size_t n = sizeof(arr) / sizeof(*arr);
    

    because it is the type of an expression with the sizeof operator.

    So the function should be declared like

    void writePrime( const int arr[], size_t n );
    

    Using two loops with two pointers within the function does not make a sense.

    Each variable is divisible by 1. So this code snippet

      i = 1;
      if (*qq % i != 0)
        continue;
      else
        prime = 1;
    

    also does not make any sense.

    And you are using initially uninitialized variable prime that must be reset before processing each element of the array.

    The function can be defined the following way

    void writePrime( const int arr[], size_t n )
    {
        for ( const int *p = arr; p != arr + n; ++p )
        {
            int prime = *p % 2 == 0 ? *p == 2 : *p != 1;
    
            for ( int i = 3; prime && i <= *p / i; i += 2 )
            {
                if ( *p % i == 0 ) prime = 0;
            }
    
            if ( prime ) printf( "%d ", *p );
        }
    
        putchar( '\n' );
    }