/* L-29 MCS 572 Wed 29 March 2006: prime tester with OpenMP
   The number to be tested for primality is typed in by the user.
   The number of threads needed for primality testing is computed.
   On copper we can use no more than 64 threads.
   Compile with "cc_r -qsmp=omp -o prime_tester prime_tester.c -lm"
   and run, typing "prime_tester" at the command prompt. */

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

int main ( int argc, char *argv[] )
{
   int n,nt;
   double dn,sn;
   int result = 1;

   printf("Give a number to test : "); scanf("%d",&n);

   dn = (double) n; sn = sqrt(dn); nt = (int) sn;

   printf("The integer square root of %d is %d...\n",n,nt);
   if (nt < 65 )
      printf("  will create %d threads.\n",nt);
   else
   {
      printf("  will create 64 threads (maximal possible).\n");
      nt = 64;
   }
   omp_set_num_threads(nt);  /* nt = #threads executed in parallel section */

   #pragma omp parallel      /* parallel section executed by all threads */
   {
      int id = omp_get_thread_num();    /* returns thread id number */
      int d = id+2;                     /* id numbers start from 0 */

      if(n % d == 0)                    /* found a divisor */      
      {
         result = d;
         printf("Thread %d found %d as divisor of %d.\n",id,d,n);
      }
   }                         /* return to the sequential world */
   if(result == 1)
      printf("No divisor for %d was found.\n",n);
   else
      printf("A divisor %d of %d was found.\n",result,n);

   return 0;
}
