-3

I wrote this program in C for prime factors but its crashing after printing first prime factor, So i need help

#include<stdio.h>
void prime(int n,int i)
{
    i=2;
    if(n%i==0)
    {
        printf("%d ",i);
        n=n/i;
        prime(n,i);
    }
    else
    {
        i++;
        prime(n,i);
    }
}
void main()
{
    int n;
    scanf("%d",&n);
    prime(n,2);
}
hnefatl
  • 5,407
  • 2
  • 22
  • 43
Alind
  • 17
  • 4

2 Answers2

2
#include<stdio.h>
void prime(int n,int i)
{
    if(n==0)
        ;
    if(n==1)
        ;
    else if(n%i==0){
        printf("%d ", i);
        n=n/i;
        prime(n,i);
    }
    else{
        i++;
        prime(n,i);
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    prime(n,2);

    return 0;
}

If you add the cases for n==0 and n==1 (and remove the i=2;), you'll be all set.


edit - removed voided main as suggested by Jonathan Leffler

Trevor Tracy
  • 336
  • 1
  • 10
  • Now that the program more or less works, it's time to point out that recursion is not a good substitute for loops in C. Try for example the number 3167361. I don't know its factors, but it overruns the stack for me. – Arndt Jonasson May 31 '18 at 13:55
  • And it's also not really very efficient: it tries all composite `i` although their factors have already been divided away. But as a first try, it's a good program. – Arndt Jonasson May 31 '18 at 14:00
  • The factors of that are: 1, 3, 9, 351929, 1055787, 3167361 – Trevor Tracy May 31 '18 at 14:02
  • The prime 351929 alone is sufficient to exhibit the problem. – Arndt Jonasson May 31 '18 at 14:05
  • Thank You @ArndtJonasson – Alind May 31 '18 at 14:12
  • Note that 9 is not a prime factor (and neither is 1): the prime factors of 3167361 are 3, 3 and 351929. – Jonathan Leffler May 31 '18 at 14:37
  • I listed all the factors @JonathanLeffler , not prime factors. But yes, you are correct – Trevor Tracy May 31 '18 at 14:39
  • See [What should `main()` return in C and C++?](https://stackoverflow.com/questions/204476/) for a discussion of why `void main()` is dubious — supported only on Windows. I realize you probably just copied the code from the question, but … – Jonathan Leffler May 31 '18 at 14:45
  • @AlindKumar you might be interested in this [Prime Factors Calculator](http://www.javascripter.net/math/calculators/primefactorscalculator.htm) to check your work. – Weather Vane May 31 '18 at 14:48
1

It's doing an infinite loop as you are resetting i every time when doing

i = 2;

But even without that, you'll probably overflow i and you don't have a recursion terminal case.

you will have to rethink your logic for this to work.

Nox
  • 832
  • 1
  • 8
  • 24