javascript – Task: find the maximum prime divisor of 600851475143

Question:

help plz. wrote the following code. does not work. as an option, I tried first to add the found prime numbers to the array and extract the last.

function prime() {
    var primeDiv = 1;    
    for (var i = 2; i < 600851475143 ; i++) {
        if ( 600851475143 % i == 0 ) {
            primeDiv = i;
        } 
        return primeDiv;  
    };    
};

console.log( prime() );

This code gives the result "1" the correct answer is 6857.
There are tons of answers in different languages, but what exactly is wrong with this code?

Answer:

Perhaps this will help (finding the largest prime number not greater than the given one)?

<script>
/*
Перебираем все цифры (N), которые оканчиваются на 1, 3, 7 или 9
(всё, что кончается на 0 или 5, явно не простое число ),
и делим их на все числа от 3 до корня от N включительно.
*/
  function PrimeFactors(n)
  {
    if (n<=2 || n==5)
      return n;
    for (var i = n; i >= 2; --i)
    {
      if (i==2 || i==5) return i;
      var i10 = i%10;
      if (i10 == 1 || i10 == 3 || i10 == 7 || i10 == 9)
      {
        var maxJ = Math.sqrt(i);
        var easy = true;
        for (var j=3; j<=maxJ; ++j)
        {
          easy = i%j != 0;
          if (!easy) break;
        }
        if (easy) return i;
      }
    }
    return 0;
  }
  document.write(PrimeFactors(600851475143 ));
</script>

took this article as a basis

PS: Finding the maximum prime divisor (the algorithm has not optimized, so you need to wait 10-20 seconds):

<script>
function SearchMaxPrimeDelitel(n)
{
  n = Math.abs(n);
  for (var d=1; d<n/2; ++d) 
    if (n%d == 0)
    {
      var i = n/d;
      if (i==5 || i==2)
        return i;
      var i10 = i%10;
      if (i10 == 1 || i10 == 3 || i10 == 7 || i10 == 9)
      {
        var easy = true;
        var maxJ = Math.sqrt(i);
        for (var j=3; j<=maxJ; ++j)
        {
          easy = i%j != 0;
          if (!easy) break;
        }
        if (easy) return i;
      }
    }
  return 1;
}
document.write(SearchMaxPrimeDelitel(600851475143 ));
</script>
Scroll to Top