Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active October 2, 2015 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lovasoa/2211013 to your computer and use it in GitHub Desktop.
Save lovasoa/2211013 to your computer and use it in GitHub Desktop.
Find prime factors of a given integer
/* prime factors
by ophir lojkine
*/
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
unsigned long *primes, primesSize, lastPrime;
void findNextPrime () {
unsigned long i=lastPrime, k;
char isprime;
for (k=primes[i]+1; i<=lastPrime; k++) {
isprime = 1;
for (i=0; primes[i]*primes[i] <= k && i<=lastPrime; i++){
if (k%primes[i] == 0){
isprime = 0;
break;
}
}
if (isprime==1){
lastPrime++;
if (lastPrime >= primesSize) {
primesSize += SIZE;
primes = realloc(primes, primesSize * sizeof(unsigned long));
if (primes==NULL){
printf("Erreur de mémoire à la ligne %d.", __LINE__);
exit(2);
}
}
primes[lastPrime] = k;
break;
}
}
}
unsigned long* primeFactors (unsigned long n) {
unsigned long i;
unsigned long *r, rSize=5, rPoint=0;
r = malloc(sizeof(unsigned long) * rSize);
if (r==NULL) {
printf("Erreur à la ligne %d", __LINE__);
exit(2);
}
for (i=0; n!=1; i++) {
if (i>=lastPrime) findNextPrime();
if (n%primes[i]==0){
r[rPoint] = primes[i];
r[rPoint+1] = 0;
r[rPoint+2] = 0;
while (n%primes[i]==0) {
r[rPoint+1]++;
n /= primes[i];
}
rPoint += 2;
if (rPoint >= rSize-1) {
rSize += 8;
r = realloc(r, rSize * sizeof(unsigned long));
if (r==NULL) {
printf("Erreur à la ligne %d", __LINE__);
exit(2);
}
}
}
}
return r;
}
int main (int argc, char **argv) {
primesSize = SIZE;
primes = calloc(primesSize, sizeof(unsigned long));
lastPrime = 0;
primes[0] = 2;
unsigned long n, *r, i;
printf ("Bienvenue dans le décomposeur en facteurs premiers.\
Tapez un nombre, sa décomposition apparaîtra. La liste des nombres premiers\
connus augmente au fur et à mesure que de nouveaux nombres premiers sont\
nécessaires pour décomposer les nombres que vous entrez.\
Pour obtenir la liste de tous les nombres premiers trouvés par le programme,\
tapez '1'.\
Pour quitter tapez '0'\n");
while (1) {
printf ("> "); scanf("%ld", &n);
if (n==1) {
for (i=0;i<=lastPrime;i++) printf ("%ld ", primes[i]);
printf("\n");
continue;
}
if (n==0) break;
r = (unsigned long*)primeFactors (n);
for (i=0; r[i] != 0; i+=2) {
printf("%ld^%ld ", r[i], r[i+1]);
}
printf ("\n");
free(r);
}
printf("Au revoir...\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment