A positive integer is entered through the keyboard. Write a function to obtain the prime factors of this number. For example, prime factors of 24 are 2, 2, 2 and 3, whereas prime factors of 35 are 5 and 7.
Using recursion:
void main()
{
int x;
printf("\nInput an integer\n");
scanf("%d",&x);
prime(x);
}
prime(int x)
{
int a;
for(a=2;a<=x;a++)
{
if(x%a==0)
{
printf("%d ",a);
prime(x/a);
break;
}
}
}
without recursion
void main()
{
int x;
printf("\nInput an integer\n");
scanf("%d",&x);
prime(x);
}
prime(int x)
{
int a;
for(a=2;a<=x;a++)
{
if(x%a==0)
{
printf("%d ",a);
x/=a;
a--;
}
}
}
Subscribe to:
Post Comments (Atom)
This was very insightful. Thank you from Argentina.
ReplyDeleteWithout recursion :
ReplyDelete/*
* prime_factors.c
*
* Created on: Jul 11, 2015
* Author: Sujay
*/
#include
#include
void main()
{
int n;
printf("\nEnter your number: ");
fflush(stdout);
scanf("%d",&n);
prime(n);
}
void prime(n)
{
int i,j,k,l,m;
m=n;
for(j=2;j<=n;j++)
{
if(j==m)
{
printf(" 1 , %d",n);
fflush(stdout);
j++;
}
else if (n%j==0)
{
printf("%d ",j);
fflush(stdout);
n=n/j;
j--;
}
else
{
continue;
}
}
}