1,105,386 Community Members

Recursion prime factors (no loops of anykind)

Member Avatar
dippatel
Newbie Poster
1 post since Jan 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

hi im told to make a program where the user enters a large number like 13195 and the prgrams gives it the highest prime factor, which i 29. now i have to do this using recursion in basic c, without using loops of any kind, so noo for, while etc. prof showed a way to call the funtion again by it self but dont really get him so thats why need a bit of help..

#include<stdio.h>
#include <math.h>
int main()
{
	long int num;
	long int prime(long int num);
	long int primefactor(long int num);

	printf("Enter the number whose prime factors are to be calculated:");
	scanf("%ld", &num);

	primefactor(num);
}

//The following is the function that detects a Prime number.  

long int prime(long int num)
{
	long int i, ifprime;

	i = 2;
	if (i <= num )
	{
		if (num % i == 0)
		{
			ifprime = 0;
		}
		else
			ifprime = 1;

		i++;
	}



	return (ifprime);
}	//The following function prints the prime factors of a number.	

long int primefactor(long int num)
{
	long int factor, ifprime = 0;

	factor = 2;
		if (factor <= num)
	{

		prime(num);
			//so that the factors are only prime and nothing else.	 
		if (ifprime)
		{
			if (num % factor == 0)	//diving by all the prime numbers less than the number itself.   
			{
				printf("%ld ", factor);
				num = num / factor;

			}
			else
			{
			factor++;	//this cannot be made a part of the for loop	 
			}
		}

	}

	
		if (factor<=num){
		primefactor();
		else{
			break;
	}

	return (0);
}
Member Avatar
VernonDozier
Posting Expert
5,632 posts since Jan 2008
Reputation Points: 2,218 [?]
Q&As Helped to Solve: 768 [?]
Skill Endorsements: 26 [?]
Featured
 
1
 

Line 31 -- i is generally a loop counter variable. There is no loop (as per your instructions), but there is also no recursion. Why does the "prime" function return a long int rather than a bool, particularly since it can only return a 0 or a 1?

Line 47 -- You call "prime", then do absolutely nothing with the return value.

Ditto line 67 -- why bother having a function return a value if you do nothing with it?

Line 69 -- break? The "break" statement is designed to break you out of a loop. The instructions say no loops and your program has none. "break" therefore makes no sense.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: