diff --git a/Find Prime Numbers/FindPrimes.py b/Find Prime Numbers/FindPrimes.py index 911728e..0e6b93c 100644 --- a/Find Prime Numbers/FindPrimes.py +++ b/Find Prime Numbers/FindPrimes.py @@ -1,3 +1,5 @@ +from math import sqrt + n = input("Masukan angka: ") str_n = str(n) angka = [] @@ -9,12 +11,29 @@ angka = list(dict.fromkeys(angka)) -def prime(n): +def prime(n: int): + """ + Function that checks whether an integer number is prime or not. + A prime number is a number which has two distinct divisors: itself and 1. + + @param n: int + @return: str + + """ + # first check if n is not negative. if n <= 0: return "Not defined" + + # 1 is not a prime + # note that 1 have only 1 distinct divisor which is itself. elif n == 1: return "Not prime" - for i in range(2, n): + + # if n >= 2 then iterate through all numbers from 2 to the square root of n + # to check if there is another number that divide n + # note that we stopped at sqrt(n) since (i divide n) -> (i/n divide n) and either one of the two (i & n/i) is below sqrt(n) + for i in range(2, int(sqrt(n)) + 1): + # i divide n is equivalent to n%i == 0 if n%i == 0: return "not prime" return "prime" @@ -24,4 +43,4 @@ def prime(n): if x == "prime": prima.append(a) -print(prima) \ No newline at end of file +print(prima)