Given two integers n and m. Check n^2 – m^2 is prime or not. n and m can be very large.
Input : n = 6, m = 5 Output : YES Input : n = 16, m = 13 Output : NO
A simple solution is to fist compute n^2 – m^2, then check if it is prime or not. n^2 – m^2 might be very large – it might not even fit into 64-bit integer. Checking primality for it certainly cannot be performed naively.
A better solution is to express n^2 – m^2 as (n-m)(n+m). This is prime if and only if n-m = 1 and n+m is a prime.
Time Complexity: O(sqrt(n+m))
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Check if a number is Prime, Semi-Prime or Composite for very large numbers
- Quick ways to check for Prime and find next Prime in Java
- Check if a prime number can be expressed as sum of two Prime Numbers
- Check whether the sum of prime elements of the array is prime or not
- Check if N is Strong Prime
- Check if two numbers are co-prime or not
- Check if N is a Factorial Prime
- Check if N is a Weak Prime number or not
- Check whether a number is Good prime or not
- Check if N is a Balanced Prime number or not
- C Program to Check Whether a Number is Prime or not
- Check whether N is a Dihedral Prime Number or not
- Check whether a number is circular prime or not
- Check if the first and last digit of number N is prime and their sum is less than K
- Check if a number is Quartan Prime or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.