Search code examples
pythonalgorithmprime-factoring

Right algorithm for finding largest prime factor


I am trying to find out the largest prime factor of any number. I am doing the program for this problem in python, but there seems to be something wrong with the algorithm that I am following. It seems to fall into an infinite loop. The program goes like this:

def prime(n):
  i=0;
  while(n!=2):
    for i in range(2,n):
        if(n%i==0):
            prime(n/i);
        else:
            continue;
    print("The highest prime factor is: "),n;

print("Enter a number to find its highest prime factor");
n=input();
prime(n);

Just point out what are the problems here and also mention if there are any other better algorithm than this one for solving this.


Solution

  • EDIT : It feels like I can't manage to be clear without some code, so here it is, with a few modification from yours :

    def prime(n):
      i=2
      while (n%i != 0 and i < n):
        i += 1
      if (i < n):
        return prime (n/i)
      else:
        print("The highest prime factor is: "),n
    
    print("Enter a number to find its highest prime factor")
    n=input()
    prime(n)
    

    However, your algorithm is not very efficient. For example, you might consider using Pollard's Rho if you want something better and not long to code. And even if you want to stick with your idea, you shouldn't do your divisibility tests like this. You may want to run an Erathostene sieve first to only test divisibility by prime factors. Or even only remember the last divisor you found in order to restart the algorithm from there, not from 2.

    For example, a little bit better code would be :

    def prime(n,a):
      i = a
      while (n%i != 0 and i*i < n):
        i += 1
      if (i*i < n):
        return prime (n/i, i)
      else:
        print("The highest prime factor is: "),n
    
    print("Enter a number to find its highest prime factor")
    n=input()
    prime(n,2)