/* L-2 MCS 275 : NumFac.c
 * factor a number into primes, extending Python */

#include <stdio.h>
#include <string.h>

int factor ( int n, char *s );
/* writes the prime factors of n to the string s */

int test ( void );
/* interactive test program */

int test ( void )
{
   int n;
   char s[80]; /* string for result */

   printf("give a natural number n : ");
   scanf("%d",&n);

   factor(n,s);

   printf(s); /* print result */

   return 0;
}

int factor ( int n, char *s )
{
   int d,r;
   char f[10]; /* string for factor */

   sprintf(s,"%d =",n);
   d = 2;
   while(d < n)
   {
      r = n % d;
      if(r == 0)
      {
         sprintf(f," %d",d);
         strcat(s,f);
         n = n/d;
         d = 2;
      }
      else
         d = d + 1;
   }
   sprintf(f," %d\n",n);
   strcat(s,f);

   return 0;
}

#include "Python.h"

static PyObject *NumFac_factor ( PyObject *self, PyObject *args )
{
   PyObject *result;
   int n; 
   char s[80];

   if(!PyArg_ParseTuple(args,"is",&n,&s)) return NULL;

   factor(n,s);

   result = (PyObject*)Py_BuildValue("s",s);

   return result;
}

static PyObject *NumFac_test ( PyObject *self, PyObject *args )
{
   test();
   return (PyObject*)Py_BuildValue(""); 
}

static PyMethodDef NumFacMethods[] =
{
   { "factor" , NumFac_factor , METH_VARARGS, 
     "factor a natural number into primes" } , 
   { "test" , NumFac_test , METH_VARARGS,
     "interactive test on prime factoring" } , 
   { NULL , NULL, 0, NULL } ,
};

static struct PyModuleDef NumFacModule = {
   PyModuleDef_HEAD_INIT,
   "NumFac",
   "prime number factorization",
   -1,
   NumFacMethods
};

PyMODINIT_FUNC
PyInit_NumFac()
{
   return PyModule_Create(&NumFacModule);
}
