[Solved] Determine if a number is prime [closed]

Introduction

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Determining if a number is prime is an important problem in mathematics, and there are several methods for solving it. In this article, we will discuss some of the most common methods for determining if a number is prime, including trial division, the Sieve of Eratosthenes, and the Miller-Rabin primality test. We will also discuss the advantages and disadvantages of each method.

Solution

//This function will take a number as an argument and return true if it is a prime number, and false if it is not.

function isPrime(num) {
//check if num is less than 2, if so, it is not a prime number
if (num < 2) { return false; } //check if num is divisible by any number between 2 and num-1 for (let i = 2; i < num; i++) { if (num % i === 0) { return false; } } //if num is not divisible by any number between 2 and num-1, it is a prime number return true; }


You are missing a bracket. If you keep your code clean it will solve the problem.

Also in your if statement you are checking if number % 2 != 0. If it does not equal to 0 then it could potentially be a prime number. So I changed it to number % 2 == 0 to fix the problem.

The other mistake is that you kept printing even after you knew that the number is not prime.

public static void isPrime(int number)
    {
        for ( int i = 2; i<Math.sqrt(number) + 1; i ++)
        {
            if ( number%i==0 ) {//If number is not a prime
                //Will print that the number is not a prime once
                System.out.println(number +" is not a prime number.");
                return ; //Will exit the method
            }
        }
        //If you reach this point then the number is prime.
        System.out.println(number +" is a prime number.");
    }

5

solved Determine if a number is prime [closed]


#include <stdio.h>

int isPrime(int n) 
{ 
    // Corner cases 
    if (n <= 1) 
        return 0; 
    if (n <= 3) 
        return 1; 
  
    // This is checked so that we can skip 
    // middle five numbers in below loop 
    if (n % 2 == 0 || n % 3 == 0) 
        return 0; 
  
    for (int i = 5; i * i <= n; i = i + 6) 
        if (n % i == 0 || n % (i + 2) == 0) 
            return 0; 
  
    return 1; 
} 
  
// Driver Program to test above function 
int main() 
{ 
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (isPrime(n)) 
        printf("%d is a prime number", n); 
    else
        printf("%d is not a prime number", n); 
  
    return 0; 
}