Chapter - 6: Functions And Pointers

A positive integer is entered through the keyboard. Write a function to obtain the prime factors of this number.


D
Sections
5
Exercises

For example, prime factors of 24 are 2, 2, 2 and 3, whereas prime factors of 35 are 5 and 7.


#include<stdio.h>
#include<conio.h>
int check_prime(int);
void pf(int);
int main()
{
	int num;
	printf("Enter a number : ");
	scanf("%d", &num);
	pf(num);
	_getch();
	return 0;
}
void pf(int num)
{
	int i;
	for (i = 2; num != 1; i++) //loop for obtaining the numbers.
	{
		if (num%i != 0)// If the number is not a factor
			continue;
		else
		{
        	//If the number is prime, so check if it is prime
			if(check_prime(i) == 1)
			{
				while (num%i == 0)
				{
					printf("%d, ", i);
					num /= i;
				}
			}
		}
	}
}

//returns 1 if prime, otherwise 0.
int check_prime(int num)
{
	int i = 2;
	while(i < num)
	{
		if(i%num == 0)
			return 0;
		i++;
	}
	if(i == num)
		return 1;
}

© 2020 Garbage Valuegarbage value logo