Data Structure & Algorithms
DSA
Introduction to problem solving
Is Prime

isPrime

Problem Description

Given a number A. Return 1 if A is prime and return 0 if not.

Note : The value of A can cross the range of Integer.

Problem Constraints

``1 <= A <= 10^9``

Input Format

``The first argument is a single integer A.``

Output Format

``Return 1 if A is prime else return 0.``

Example Input

``````Input 1:
A = 5

Input 2:
A = 10``````

Example Output

``````Output 1:
1

Output 2:
0``````

Example Explanation

``````Explanation 1:
5 is a prime number.

Explanation 2:
10 is not a prime number.``````

Output

Java
``````public class Solution {
public int isPrime(int A) {
if (A <= 1) return 0;
if (A <= 3) return 1;
if (A % 2 == 0 || A % 3 == 0) return 0;
for (int i = 5; i * i <= A; i += 6) {
if (A % i == 0 || A % (i + 2) == 0)
return 0;
}
return 1;
}
}``````
Python
``````class Solution:
def isPrime(self, A):
if A <= 1:
return 0
if A <= 3:
return 1
if A % 2 == 0 or A % 3 == 0:
return 0
i = 5
while i * i <= A:
if A % i == 0 or A % (i + 2) == 0:
return 0
i += 6
return 1``````
JavaScript
``````function isPrime(A) {
if (A <= 1) return 0;
if (A <= 3) return 1;
if (A % 2 === 0 || A % 3 === 0) return 0;
for (let i = 5; i * i <= A; i += 6) {
if (A % i === 0 || A % (i + 2) === 0)
return 0;
}
return 1;
}``````