Objective

Create a function to determine if a given integer is a prime number.

Difficulty

Easy

Description

A positive integer greater than ::1:: that is only divisible by two integers, ::1:: and the integer itself, is called a prime number.

For instance, ::2:: is a prime number since it is only divisible by ::1:: and ::2::. So is the integer ::3:: — it's only divisible by ::1:: and ::3::. The first 10 prime numbers are ::2::, ::3::, ::5::, ::7::, ::11::, ::13::, ::17::, ::19::, ::23::, ::29::.

Similarly, a number greater than ::1:: that is divisible by more than 2 integers is called a composite number.

For instance, ::4:: is a composite number since it is divisible by ::1::, ::2:: and ::4::. The first 10 composite numbers are ::4::, ::6::, ::8::, ::9::, ::10::, ::12::, ::14::, ::15::, ::16::, ::18::.

In this exercise, you have to create a function is_prime() that checks whether a given integer is prime or not. Such a function, or algorithm, is usually called a primality testing function.

Here's how the function should look:

function is_prime($n) {
   // Code here...
}

It should return true if the given integer $n is prime, or else false. However, if the given argument is not an integer, or is less than or equal to 1, the function should return NULL.

Below shown is an example usage of the function:

<?php

function is_prime($n) { /* ... */ }

var_dump(is_prime(2));
var_dump(is_prime(3));
var_dump(is_prime(4));
var_dump(is_prime(5));

// Argument is <= 1, hence NULL is returned.
var_dump(is_prime(1));
var_dump(is_prime(0));
var_dump(is_prime(-10));

// Argument is not int, hence NULL is returned.
var_dump(is_prime(2.0));
bool(true) bool(true) bool(false) bool(true) NULL NULL NULL NULL

Hints