![]() |
Why do we check up to the square root of a number to determine if that number is prime?Prime numbers are natural numbers greater than 1 which are divisible only by 1 and itself. Examples include 2, 3, 5, 7, 11, 13, etc. (1 is neither prime nor composite). Here is the code to check whether a number is prime or not. As, the loop checks for each number until the sqrt(n), where n is the number to be checked, to be a factor of n. The reason for checking up to sqrt(n) only is explained as follows:- Consider a natural number N (greater than 1) which exists as a product of two numbers a and b (assume a<=b) that is
By multiplying the relation a ≤ b by a, the relation becomes:
By multiplying the relation a ≤ b by b, the relation becomes:
From the above-mentioned inequalities, the relation becomes:
We know that N = a * b, so by replacing a * b with N, the following relation is obtained:
Taking the square root of the equation, considering both a and b as positive numbers, we get:
So, according to the above relation, it can be concluded that one of the factors of a non-prime number will definitely be less than or equal to sqrt(N).
Examples:Example: N = 16 √16 = 4 Example: N = 36 √36 = 6 |
Reffered: https://www.geeksforgeeks.org
Analysis Of Algorithms |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |