I wrote this code to check whether the user-entered integer is prime. If not, the program is to display the integer's factorization as a product of primes in ascending order.
For example, if you enter 17, the program should print
"17 is a prime number." ;
if you enter 24, the program should print
"24 is not a prime number.
24=2x2x2x3"
Right now, if you enter a prime number, my program will correctly identify it as such. If you enter a non-prime number, the program will correctly identify it as non-prime, but will not print the correct prime factorization.
e.g., if you enter 25, the program will print:
"25 is not a prime number.
25=5x7x0x0x0x0x1"
if you enter 24, you'll get this:
"24 is not a prime number.
24=2x5x0x2x3"
I can't identify what is wrong with my code. I think the way I worked the array is wrong. But I have no clue. Please help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <stdio.h>
#include <math.h>
int countprime, primefactorstorage[];
void getprimefactors(int);
void getprimefactors (int x) /*x will be replaced with the value entered by the
user (n)*/
{
countprime=0; /*the number of prime factors found thus far is 0*/
while(x%2==0) /*check if x is divisible by 2, the smallest prime number and
the only even prime number*/
{
primefactorstorage[countprime]=2; /*store 2 in primefactorstorage*/
countprime++;
x=x/2; /*reduce n further by 2 so in the end n will have no
divisor that is a multiple of 2*/
}
/*At this point, x is no longer even, so we start dividing x with odd
numbers*/
int i=3;
for (i=3; i<=sqrt(x); i=i+2) /*use i+2 because only want to sample odd
numbers to divide x stop until i>sqart(x)
because non-prime numbers have no prime
factor greater than its square root*/
{
while(x%i==0) /*the loop continues as long as x is divisible by i*/
{
primefactorstorage[countprime]=i; /*store i in primefoactorstorage*/
countprime++;
x=x/i; /*devide n further by i so in the end n will have no
divisor that is a multiple of i*/
}
}
/*now what remains as x if it's greater than 2 is an odd prime factor*/
if (x>2);
{
primefactorstorage[countprime]=x;
countprime++;
}
return;
}
int main()
{ int n, j;
printf("Enter a positive integer that is greater than 1\n");
scanf("%d", &n);
if(n==2)
printf("2 is a prime number.");
else
{
getprimefactors(n);
if (countprime==1)
printf("%d is a prime number.\n", n);
else
{
printf("%d is not a prime number.\n %d=", n, n);
for (j=0; j<countprime-1; j++)
printf("%dx", primefactorstorage[j]);
printf("%d", primefactorstorage[countprime-1]);
}
}
return 0;
}
|