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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
No comments:
Post a Comment