This function will take a number (n) and give you its prime factorization.
It runs fine, but I have a sneaking suspicion that there is a more "intuitive" way for the program to take the prime factorization of a negative number--that is, I want the program to be able to factor out a -1 instead of me just printing it.
Code://Factors.c//Prime Factorization #include<stdio.h> #include<math.h> #include<stdlib.h> #include<stdbool.h> Primality(); //primality function which will determine if a number is prime. //long Primality(long n) //{ //check to see if the number is a multiple of 2(ie the number is even) and is not equal to 2 // if(n % 2 == 0 && n != 2) // { // return false; //if the number is even or equal to 2, return false and do not count these numbers // }//end if //once we determine that a number is not even or equal to 2, we can check the odds. // for(long i = 3; i * i <= n; i += 2) // { // if(n % i == 0) // { // return false; // }//end if // }//end for // return true; //}//end function primality int main() { long n;//user generated number long i;//incrementer printf("Enter a number to get its prime factorization: "); scanf("%ld", &n); //if the number is prime, state so if(Primality(n)) { printf("%ld: This number is prime\n", n); }//end if //if number is negative, take the absolute value of the number, but indicate that //one of the factors of this number is negative 1 if(n < 0) { n = abs(n); printf("-1\n"); }//end if //if the number is a composite number else { printf("The Prime factorization of %ld: \n", n); }//end else //for each potential factor, i for(i = 2; i * i <= n; i++) { //if i is a factor of N, repeatedly divide it out while (n % i == 0) { printf("%ld\n", i); n = n / i; }//end while }//end for //if the biggest number only occurs once, n > 1 if (n > 1) printf("%ld\n", n); }//end main



1Likes
LinkBack URL
About LinkBacks



