Solved

# SEMANTIC ERROR with while loop in C program

Posted on 2006-07-06

I'm using a while loop to calculate prime factors. I'm getting the prime factors, but I'm getting TWO sets of each one. So, for 100 (primes should be just 2 and 5, I'm getting 2 2 5 5. Could someone please take a look at my code (especially my while loop) and suggest where my error might be? Any other general suggestions on how to improve what I've written would also be appreciated.

------------------------------------MY CODE-------------------------------------------------------

// prime factorizarion.

#include <stdio.h>

// isPrime function

// return 1 if number prime

int isPrime(int n)

{

int i = 2;

while ( i <= n/2 )

{ if ( (n % i) == 0 )

//this is not a prime

return 0;

i++;

}

// this is a prime

return 1;

}

// prime factor a number

int main()

{

int prime; // prime divider

int num; // number to find primes factors of

// get number

printf("Enter a number greater than 1: ");

scanf("%d",&num);

while(num > 1)

{

prime = 2; // start with lowest prime

// To prime factor a number, begin dividing by the smallest possible prime

// and continue until the quotient is a prime number.

while(!isPrime(num))

{

// test if num is prime

if((num % prime)==0)

{

printf("%d ",prime); // print out factor

num = num / prime;

}

// find next prime

else

{

prime++;

while(!isPrime(prime))

{

prime++;

}

}

}

// print out last factor

printf("%d\n",num);

// get next number

printf("Enter a number greater than 1: ");

scanf("%d",&num);

}

printf("\n");

return 1;

}