Friday, May 23, 2014

Prime Factors of a Number using Recursion - C Program

Problem Question


A positive integer is entered through the keyboard, write a program to obtain the prime factors of the number. Modify the function suitably to obtain the prime factors recursively.

Explanation of Problem


In this program, we need to devise a function that would find the prime factors of a number recursively.

Code


#include <stdio.h>
/**@Title: PrimeFactorsRec.c*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 23-05-2014*
*/

void prime(int x)
{
 int a; //loop counter
 for( a = 2; a <= x; a++ )
 {
  if( x % a == 0 )
  {
   printf("%d ",a);
   prime(x/a);
   break;
  }
 }
}

int main()
{
 int number;
 printf("\n\nEnter a number: ");
 scanf("%d", &number);
 prime(number);
 printf("\n\n");
 system("pause");
 return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This function has to be named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

 for( a = 2; a <= x; a++ )
 {
  if( x % a == 0 )
  {
   printf("%d ",a);
   prime(x/a);
   break;
  }
 }


This is the part of code where the calculation takes place. The for loop, for( a = 2; a <= x; a++ ) keeps incrementing the counter, 'a'. We use it to divide the number that user entered. The if condition, if( x % a == 0 ) checks if the number is divisible by the current value of the counter 'a'. If that is the case, we print the number 'a' and call our function prime recursively, but this time with a value 'x/a' rather than 'x'. With this, we are not stuck in an infinite recursion of printing the same prime factor. Since we keep on dividing the number by the prime factor found in last iteration, we are sure of segregating any multiples of this 'found prime factor'. Hence, we avoid getting the composite factors, since the counter always starts at 2. Thus only prime factors get printed on the screen, with a single space separating each of them.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



7 comments:

  1. Plz tell me why the break statement is used in this program.Is it necessary to use it.

    ReplyDelete
    Replies
    1. yes it is extremely important. you can test the program without break and with break for a sample run of input '5000' for example.

      If you need an explanation, here it is:

      Consider a sample run with input 10. prime(10) is called.
      for loop with a=2 executes. x%a, i.e., 10%2 is 0. Hence the 'if' condition is true. 2 is primted. The control calls the function prime(x/a), i.e. prime(10/2), i.e., prime(5). The break is not executed as yet. Let's call this break 1.

      As yet the output is: 2

      prime(5) is called, the for loop executes from a=2 to a<=5. The if condtion is true at a=5. Thus 5 is printed. prime(5/5), i.e. prime(1) is called. Break of this iteration not yet executed. Let's call this break 2.

      As yet the output is: 2 5

      Now the for loop starts for a=2 to a<=1. Hence the condition fails, and for loop doesn't run. Hence the control comes to break 2. Consider this break was not there, then a would be incremented, the for loop test fails ,the control exits for loop, and hence prime(5). Now the control reaches break 1. Now currently in this iteration we have a=2 and x=10. If break was not there, the for loop would increment 'a'. Hence the 'if' condition becomes true at a=5 and a=10.

      Thus the output would be: 2 5 5 10 which is not expected,
      instead of 2 5 which is expected.

      Hence the break statement is required. It forbids the control to reenter that iteration of the for loop which is no longer required since we only need prime factors. If you will run this program without break for a larger number, you will get not just such unexpected outputs, but the non-prime factors of the input as well.

      I hope this clarifies your doubt.

      Good evening.

      Delete
    2. Thanks for making this clear

      Delete
  2. great thank you so much, i was stuck with this program and wasted 5 hours to solve by self. but didnt get success. lastly find this page blog on internet, helped me, thank you. but i regret to see the soluton is very easy understandable, why this thought could not come in my mind.

    ReplyDelete
  3. Thanks a lot,i was stuck in this program. Can you tell me which compiler you use??

    ReplyDelete
  4. Oh sorry...i found it in the comments...sorry to disturb ya :/

    ReplyDelete

Need help?