I'm going to address the coding, asking if an algorithm is a best approach is somewhat opinion based and to be avoided.
Avoid using abbreviations such as no. in prompts, it is better to use real words.
Iterative approaches may be better than recursive approaches because they use less resources (less memory for instance on the stack).
There is no reason to have a function prototype for the function primefactors if you swap the order of the functions primefactors() and main(). In C it is very common for the last function in a file to be main().
The indentation of the last } is problematic and should be corrected.
Leave horizontal space between operators such as , and & in all statements. that makes the code much more readable and easier to maintain. Examples:
scanf("%d", &num); printf("%d", primefactors(num));
and
for(int i=2; i <= sqrt(n); i++){ while(n % i == 0){ printf("%d ", i); return primefactors(n / i); } } if(n > 2) return(n);
Leave vertical spacing between functions and sometimes separating logical blocks of code.
#include<stdio.h> #include<math.h> int primefactors(int n){ for(int i = 2; i <= sqrt(n); i++){ while(n % i == 0){ printf("%d ", i); return primefactors(n / i); } } if(n > 2) return(n); } int main() { int num; printf("Enter a no:-\n"); scanf("%d", &num); printf("%d", primefactors(num)); return 0; }
Update with testing:
I have altered the code in the following way to get the prime factors for 2 through 100, the code fails on any power of 2, returning an unknown value for the final power of 2. It works properly in all other cases. This is approximately a 7% failure rate, an edge case fails.
#include<stdio.h> #include<math.h> int primefactors(int n) { for (int i = 2; i <= sqrt(n); i++) { while (n % i == 0) { printf(" %d ", i); return primefactors(n / i); } } if (n > 2) return(n); } int main() { for (int i = 2; i <= 100; i++) { printf("primefactors(%d) = ", i); printf("%d ", primefactors(i)); printf("\n"); } return 0; }
runs properly and I have tested it against various test cases(there indentation at the end ofprimefactors()is inconsistent) please add the required behaviour to the question -primefactors()' return value looks undefined for many values ofn. What is the required output for, say, 126? Consider adding the test code to the question, making it unmistakable when wanting it excluded from review. \$\endgroup\$