Prime Numbers JavaScript

后端 未结 11 1121
长发绾君心
长发绾君心 2020-12-08 11:47

Can someone please give me guidance on getting the primenumbers here? This is homework so I don\'t want the answer but some pointers would be greatly appreciated. It\'s real

相关标签:
11条回答
  • 2020-12-08 12:18

    I considered the following in my implementation: Prime numbers are "natural numbers" and it is possible for negative values to be prime numbers. This is a more definitive solution with input sanitation:

    function isPrime(num) {
        //check if value is a natural numbers (integer)
        //without this check, it returns true
        if (isNaN(num) || num % 1 !== 0) {
            return false;
        }
        num = Math.abs(num); //*negative values can be primes
        if (num === 0 || num === 1) {
            return false;
        }
        var maxFactorNum = Math.sqrt(num);
        for (var i = 2; i <= maxFactorNum; i++) {
            if (num % i === 0) {
                return false;
            }
        }
        return true;
    }
    
    //this method in action
    for (var i = 1; i <= 40; i++) {
        console.log(i + (isPrime(i) ? ", isPrime" : ""));
    }
    //checking anomalies
    console.log(isPrime(1.22));
    console.log(isPrime(1.44));
    console.log(isPrime("string"));

    I hope my answer proves to be more readable code that also uses best practices. For example, some answers leave the square root calculation in the loop causing the method to run that calculation on every loop.

    0 讨论(0)
  • 2020-12-08 12:18

    This is my Answer

    var isPrime = function (n) {
      if (n < 2) {
        return false;
      } else if (n === 2) {
        return true;
      }
      for (var i = 2; i < n; i++) {
        if (n%i === 0) {
          return false;
        } else if (i === n-1) {
          return true;
        }
      }
    }
    console.log(isPrime(7));

    0 讨论(0)
  • 2020-12-08 12:20

    Here's the fastest way to calculate primes in JavaScript, based on the previous prime value.

    function nextPrime(value) {
        if (value > 2) {
            var i, q;
            do {
                i = 3;
                value += 2;
                q = Math.floor(Math.sqrt(value));
                while (i <= q && value % i) {
                    i += 2;
                }
            } while (i <= q);
            return value;
        }
        return value === 2 ? 3 : 2;
    }
    

    Test

    var value, result = [];
    for (var i = 0; i < 10; i++) {
        value = nextPrime(value);
        result.push(value);
    }
    console.log("Primes:", result);
    

    Output

    Primes: [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
    

    It is very fast, because:

    • It aligns the loop limit to an integer;
    • It uses a shorter iteration loop, skipping even numbers.

    It can give you the first 100,000 primes in about 130ms, or the first 1m primes in about 4 seconds.

        function nextPrime(value) {
            if (value > 2) {
                var i, q;
                do {
                    i = 3;
                    value += 2;
                    q = Math.floor(Math.sqrt(value));
                    while (i <= q && value % i) {
                        i += 2;
                    }
                } while (i <= q);
                return value;
            }
            return value === 2 ? 3 : 2;
        }
    
        var value, result = [];
        for (var i = 0; i < 10; i++) {
            value = nextPrime(value);
            result.push(value);
        }
    
        display("Primes: " + result.join(', '));
    
        function display(msg) {
            document.body.insertAdjacentHTML(
                "beforeend",
                "<p>" + msg + "</p>"
            );
        }

    0 讨论(0)
  • 2020-12-08 12:22
    function isPrime(number) {
    
      // Immediate exit cases
      switch(true){
        case (number < 2):
          return console.log("Please enter a number greater than or equal to 2.")
        case (number === 2 || number === 3):
          return console.log(number + " is a prime number!")
      }
    
      // Process number if it does not meet above requirements
      var num = Math.floor(Math.sqrt(number))
    
      for(var i = 2; i <= num; i++) {
        if(number % i === 0)
          return console.log(number + " is not a prime number")
        else
          return console.log(number + " is a prime number!")
      } 
    }
    
    isPrime(27) // 27 is a prime number!
    isPrime(30) // 30 is not a prime number
    isPrime(55) // 55 is a prime number!
    isPrime(2)  // 2 is a prime number!
    
    0 讨论(0)
  • 2020-12-08 12:26

    Here's a simple "sieve" for prime numbers, which can be easily understood, and although it is a naive approach (as opposed to sophisticated efficient prime number tests such as the AKS test), it is pretty fast (10000 numbers tested in < 1 sec). It stores the found prime numbers in the array prim[] and tests by using the modulo function (%):

    The loop tests against already found prime numbers and exits if it is no prime number, i.e. if the modulo result is 0 (regard the expression i % prim[j])===0). Otherwise, it adds it to the list of found prime numbers.

    Note that because the only even prime number is 2, the loop step is 2 rather then 1, because from 3 onwards there can't be any further even prime numbers.

    var MaxNum = 10000;
    var prim;
    
    function Main() {
      MaxNum = GetMaxNum();
      prim = CalculatePrimes(MaxNum);
      CheckSome();
    }
    
    function CalculatePrimes(pMaxNum) {
      Console.WriteLine("Calculating until " + pMaxNum + "...");
      var _prim = [2];
      if (pMaxNum > 2) {
        for (var i = 3; i < pMaxNum; i += 2) {
          var is_prim = true;
          if (_prim.length > 0) {
            for (var j = 0; j < _prim.length; j++) {
              if ((i % _prim[j]) === 0) {
                is_prim = false;
                break;
              }
            }
          }
          if (is_prim) {
            _prim.push(i);
          }
        }
      }
      Console.WriteLine("Prime numbers:");
      for (var i = 0; i < _prim.length; i++) {
        Console.Write(_prim[i] + " ");
      }
      Console.WriteLine();
      Console.WriteLine("Found " + _prim.length + " prime numbers.");
      Console.WriteLine();
      return _prim;
    }
    
    // test some individual pre-calculated numbers
    
    function CheckSome() {
      var num1 = prim[prim.length - 1];
      var num2 = num1 - 1;
      Console.WriteLine("Test: " + num1.toString() + ". Is it a prime number? " + Is_prime(num1));
      Console.WriteLine("Test: " + num2.toString() + ". Is it a prime number? " + Is_prime(num2));
    }
    
    function Is_prime(n) {
      if (n > MaxNum) throw "ERROR: n must be <" + MaxNum + "!";
      if (prim.indexOf(n) === -1)
        return false;
      else
        return true;
    };
    
    
    // ------------ HELPERS to display on screen ------------
    var Console = {
      Section: 1,
      SectionId: "#section1",
      NewSection: function() {
        var $currentSection = $(this.SectionId);
        this.Section++;
        this.SectionId = "#section" + this.Section.toString();
        $currentSection.before('<div id="section' + this.Section.toString() + '"></div>');
      },
      Write: function(str) {
        $(this.SectionId).append(str);
      },
      WriteLine: function(str) {
        if (str !== undefined && str !== null && str !== "") this.Write(str);
        this.Write("<br/>");
      }
    };
    
    
    var GetMaxNum = function() {
      var result = $("#MaxNumSelect option:selected").val();
      return result;
    }
    
    $(document).ready(function() {
      $("#MaxNumSelect").change(function() {
        MaxNum = GetMaxNum();
        Console.NewSection();
        Main();
        Console.WriteLine("---------------------------------");
      });
      Main();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>Select max number:&nbsp;
      <select id="MaxNumSelect">
        <option value="10000" default="default">10000</option>
        <option value="100">100</option>
        <option value="1000">1000</option>
        <option value="100000">100000</option>
      </select>
    </div>
    
    <div id="results">
      <div id="section1"></div>
    </div>

    In the above example, we have tested the first 10000 natural numbers. To decide if a given number is a prime number, you simply check if it is contained in the array prim:

    function Is_prime(n) {
        if (n>MaxNum) throw "ERROR: n must be <"+CalcToNum+"!";
        if (prim.indexOf(n)===-1)
          return false;
        else
          return true;
    };
    

    Of course, in order for this to work the prime numbers need to be pre-calculated.

    Example: alert(Is_prime(25)); - returns false, because 25 is no prime number.

    Note: The number range must be checked, because the function Is_prime can decide only for numbers which are previously tested by the sieve above. If the array is too small for the number to check (i.e. if not enough prime numbers are pre-calculated), an error is thrown.

    0 讨论(0)
  • 2020-12-08 12:26

    In your if statement you got

    if(n%i !==0 && n%2 !==0 && n%3 !== 0)
    

    you for loop is going till i >= 2, so the n%2 !== 0 is useless, when i = 2, your if would look like:

    if(n%2 !==0 && n%2 !==0 && n%3 !== 0)
    

    Thats 2x the same check, the same is for n%3, its already checked :).

    you should keep a bool to check the n%i !== 0, if it never reach this it's a prime.

    Good luck with your homework :).

    0 讨论(0)
提交回复
热议问题