Hi,
im having some trouble with this program that is supposed to find the prime factors of a number. More specificly im having truoble with the extern part. I must not understand the correct syntax of extern, but ive looked for helpfull tutorials and cant find any. Could someone explain to me the correct syntax of extern, and tell me what is wrong with my program.
Thanks
Code:
#include <stdio.h>
#include <math.h>
extern int primefactors[100],index=0;
void factortree(int number);
int isprime(int prime);
int main(void) {
int number2factor;
printf("Input a number to factor:");
scanf("%d",&number2factor);
factortree(number2factor);
printf("\nPrime Factors of %d are\n",number2factor);
for(;index>=0;index--)
(index==0) ? printf("primefactors[index]") : printf("primefactors[index] * ");
getchar();
return 0;
}
void factortree(int number) {
int i,factor;
if (number<0)
number*=-1;
if (number==1)
return;
for (i=(int)sqrt(number);i>=2; i--) {
if ((number % i) == 0) {
factor=number/i;
printf("a factor of %d is: %d * %d\n",number,factor,i);
}
if (isprime(i))
{
primefactors[index]=i;
index++;
}
else {
printf("i=%d is not prime\n",i);
factortree(i);
}
if (isprime(factor)) {
primefactors[index]=i;
index++;
}
else {
printf("factor=%d is not prime\n",factor);
factortree(factor);
}
}
}
int isprime(int prime) {
int i;
if (prime==1 || prime==2)
return 1;
for (i=2; i<sqrt(prime); i++) {
if ((prime % i) == 0)
return 0;
}
return 1;
}