AD1

Saturday, 12 November 2016

Prime factors

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.

solution 

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <stdbool.h>
bool is_prime(int n) // afunction to check if the number is prime or not
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
else
{
continue;
}
}
return true;
}
void prime_factors(unsigned int x) // accept integer x to find its prime factors
{
while(x>0)
{
int n=2;
again:while(x%n==0)
{
x/=n;
printf("%d ",n);
}
back: if(is_prime(++n))
{
goto again;
}
else {goto back;}
}
printf("error! enter positive integer\n");
return;
}
int main()
{
int n;
printf("enter any integer \n");
scanf("%d",&n);
printf("prime factors of %d are \n",n);
prime_factors(n);
return 0;
}
view raw primefactors.c hosted with ❤ by GitHub

No comments:

Post a Comment