/* factors.c -- (C) Geoffrey Reynolds, May 2006.

   Factors file routines and misc factoring related functions.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
*/

#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include "sr5sieve.h"
#if CHECK_FACTORS
#include "arithmetic.h"
#endif

const char *factors_file_name;

void save_factor(uint32_t k, int32_t c, uint32_t n, uint64_t p)
{
  FILE *factors_file;

  factors_file = xfopen(factors_file_name,"a",error);

  if (fprintf(factors_file,"%"PRIu64" | %s\n",p,kbnc_str(k,n,c)) < 0)
    error("Could not write to factors file `%s'.",factors_file_name);

  xfclose(factors_file,factors_file_name);
}

#if CHECK_FACTORS
int is_factor(uint32_t k, int32_t c, uint32_t n, uint64_t p)
{
  uint64_t res;

  assert(c == -1 || c == 1);
  assert(p > 0);

  mod64_init(p);
  res = mulmod64(powmod64(BASE,n,p),k,p);
  mod64_fini();

  return (c < 0) ? (res == 1) : (res == p-1);
}
#endif
