How to find the largest prime factor of any number through php ?

+2 votes
36 views
asked Jan 11, 2017 in PHP by Rohit Singh (61,782 points) 35 133 354

1 Answer

+2 votes
answered Jan 11, 2017 by Abhishek Kumar (14,593 points) 5 9 35

Let take the number be  600851475143, so to find the largest prime factor run the following code

Result : 6857

<?php
$max = 600851475143;
$l_num = 0;
for ($j = floor(sqrt($max)) / 2; $j >= 2; $j--) 
{
  if (!($j % 2)) {
    continue;
  }
  $d = 3;
  $x = sqrt($j);
  while (($j % $d) && $d < $x) {
    $d += 2;
  }
  if (((!($j % $d) && $j != $d) * 1) == 0) 
  {
    if (!($max % $j)) 
    {
      $l_num = $j;
      break;
    }
  }
}
echo $l_num;

?>

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

One Thought Forever

“There is a close connection between getting up in the world and getting up in the morning.“
– Anon
~~~*****~~~

...