Pelles C forum

Pelles C => General discussions => Topic started by: Nazmul on October 24, 2004, 02:49:00 PM

Title: prime numbers
Post by: Nazmul on October 24, 2004, 02:49:00 PM
Hey i was trying to write a program that accepts an user input and displays all the prime factors of that number. But i can'nt get my program working can someone please point out where the mistake is or give me hints i would be highly obliged if anyone does.

#include <stdio.h>
#include <math.h>

int primefactor(int a);


int main()
{
   int a;
   printf("Please enter a number: ");
   scanf("%d",&a);
   primefactor (a);
   return 0;
}

int primefactor(int a)
{
   int b,i;
   int prime= 2&&5&&7&&11&&13&&17&&19&&23&&29&&31;
   for(i=1; i<=100; i++)
   {
      b=a/i;
         
      //printf("  %lf \n",b);
      if(a%i==0)
      {
          //printf("Display the factors %d %t %t  %t %d\n",b,i);
      }
      
             }
              if(a%i==prime)
          {
             printf("display the prime factors %d \n",b);
          }
   return 0;
}
Title: Primes
Post by: wbhart on May 01, 2005, 01:13:48 AM
Smells like a comp sci assignment to me.

So here is a hint.

The line

int prime= 2&&5&&7&&11&&13&&17&&19&&23&&29&&31;

doesn't make a whole lot of sense. Try defining an array of integers, with the primes in it, then search through the array to see if your factor is in there. If so, then print it. The way you've done it, this will mean a second loop to test against each element of your prime array.

Of course this will only print each prime factor in your number, once. So a number like 12 = 2x2x3 will only output 2 and 3. But maybe you can find a way to change your code so it fixes that problem.

Bill.
Title: prime numbers
Post by: project_00 on May 05, 2005, 03:13:41 PM
A simple say is to test whether it is divisible by 2 and then loop, testing if it is divisible by any odd number from 3 to the square root of the number that the user entered.
Alternatively, you can use the sieve of erasthoesene(or sonething) to get all the prime numbers up to the square root of the user's number, then see if these numbers divide the user's number.
Title: prime numbers
Post by: project_00 on May 05, 2005, 06:07:52 PM
Actually it should read "A simple say is to test whether it is divisible by 2 and then loop, testing if it is divisible by any prime number from 3 to the square root of the number that the user entered. "

Which brings up the question how do you know what the prime numbers are? :oops:
So I think should stick to the 2nd method