Thread: Find Prime Factors Of Given NUmber

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    75

    Find Prime Factors Of Given NUmber

    how to write i tried as follows but it prints all numbers.
    i want to print only prime factors of number, also i want it using for loop not while loop can anyone help me. also plz explain me each step bcoz im new in using for loop

    Code:
    #include<stdio.h>int main(){
      int num,i=1,j,k;
      printf("\nEnter a number:");
      scanf("%d",&num);
      for(i=1;i<=num;i++){
    if(num%i==0)
    prime(i);
    printf("%d\n",i);
    }
    }
    prime(int i)
    {
        int j,flag;
        for(j=2;j<i;j++)
        {
            if(j%i==0)
            flag=1;
            break;
            if(flag==1)
            return 0;
            return i;
        }
    }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    You can actually structure this algorithm in such a way that a primality test is not necessary. Simply find the smallest number that divides num, and then divide as much as you can, so that the divisor HAS to be prime.
    Code:
    void factorize(long num)
    {
        long i = 2;
        while(num > 1) {
            while(num % i == 0) {
                num /= i;
                printf("%d  ", i);
            }
            ++i;
        }
        printf("\n");
    }

  3. #3
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    Hodor likes prime numbers. They are the only real natural numbers after all.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 02-19-2009, 10:32 PM
  2. Replies: 15
    Last Post: 11-25-2007, 03:47 PM
  3. Replies: 3
    Last Post: 03-29-2005, 04:24 PM
  4. Find all factors of a number
    By Spono in forum C Programming
    Replies: 5
    Last Post: 10-23-2003, 01:23 AM

Tags for this Thread