diff --git a/alg_ex_1.py b/alg_ex_1.py new file mode 100644 index 0000000..a73824e --- /dev/null +++ b/alg_ex_1.py @@ -0,0 +1,34 @@ +# Алгоритм Евклида. Нахождение "Наибольшего Общего Делителя (НОД)" + +# Рекурсивная реализация алгоритма Евклида. --> GCD1 +# Euclidean algorithm. An efficient method for computing the greatest common divisor (GCD). + +def gcd1(a, b): + if b == 0: + return a + else: + return gcd1(b, a % b) + +if __name__ == '__main__': + a = int(input('Please enter the 1st argument: ')) + b = int(input('Please enter the 2nd argument: ')) + print(gcd1(a, b)) + +# Метод последовательного вычитания (классический) --> GCD2 +# import sys +# +# sys.setrecursionlimit(2000) + +def gcd2(a, b): + while a != b: + if a > b: + a = a - b + else: + b = b - a + return a + +if __name__ == '__main__': + a = int(input('Please enter the 1st argument: ')) + b = int(input('Please enter the 2nd argument: ')) + print(gcd2(a, b)) + diff --git a/alg_ex_2.py b/alg_ex_2.py new file mode 100644 index 0000000..6147663 --- /dev/null +++ b/alg_ex_2.py @@ -0,0 +1,75 @@ +import math + +# Решето Эратосфена + +def Eratosthenes(n): + a = [0] * n # создание массива с n количеством элементов + for i in range(n): # заполнение массива ... + a[i] = i # значениями от 0 до n-1 + + # вторым элементом является единица, которую не считают простым числом + # забиваем ее нулем. + a[1] = 0 + + m = 2 # замена на 0 начинается с 3-го элемента (первые два уже нули) + while m < n: # перебор всех элементов до заданного числа + if a[m] != 0: # если он не равен нулю, то + j = m * 2 # увеличить в два раза (текущий элемент простое число) + while j < n: + a[j] = 0 # заменить на 0 + j = j + m # перейти в позицию на m больше + m += 1 + + # вывод простых чисел на экран (может быть реализован как угодно) + b = [] + for i in a: + if a[i] != 0: + b.append(a[i]) + + del a + return b + +# Решето Аткина + +def Atkin(nmax): + """ + Returns a list of prime numbers below the number "nmax" + """ + is_prime = dict([(i, False) for i in range(5, nmax + 1)]) + for x in range(1, int(math.sqrt(nmax)) + 1): + for y in range(1, int(math.sqrt(nmax)) + 1): + n = 4 * x ** 2 + y ** 2 + if (n <= nmax) and ((n % 12 == 1) or (n % 12 == 5)): + is_prime[n] = not is_prime[n] + n = 3 * x ** 2 + y ** 2 + if (n <= nmax) and (n % 12 == 7): + is_prime[n] = not is_prime[n] + n = 3 * x ** 2 - y ** 2 + if (x > y) and (n <= nmax) and (n % 12 == 11): + is_prime[n] = not is_prime[n] + for n in range(5, int(math.sqrt(nmax)) + 1): + if is_prime[n]: + ik = 1 + while (ik * n ** 2 <= nmax): + is_prime[ik * n ** 2] = False + ik += 1 + primes = [] + for i in range(nmax + 1): + if i in [0, 1, 4]: + pass + elif i in [2, 3] or is_prime[i]: + primes.append(i) + else: + pass + return primes + +assert (Atkin(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]) + + +if __name__ == '__main__': + print('Eratosthenes = ', Eratosthenes(10000)) + print('Atkin = ', Atkin(10000)) + if Eratosthenes(10000) == Atkin(10000): + print('All primes the same!!! Excellent!!!') + else: + print('Something goes wrong(((!') \ No newline at end of file diff --git a/ex1_01_calc_delta_with_time.py b/ex1_01_calc_delta_with_time.py new file mode 100644 index 0000000..3b37fb9 --- /dev/null +++ b/ex1_01_calc_delta_with_time.py @@ -0,0 +1,29 @@ +import alg_ex_1 +import sys +import time + +orig_stdout = sys.stdout +f = open('ex1_01_module_time_output.txt', 'w') +sys.stdout = f + +print(f'{time.ctime(time.time())}\n') + +# Рекурсивная реализация алгоритма Евклида. --> GCD1 (n * e-06 = n / 10 ^ 6) +start1 = time.time() +alg_ex_1.gcd1(10000000, 90) +delta1 = (time.time() - start1) +print(f'Delta GCD1 (Recursion realization of Euclidean algorithm) = {delta1:.{10}}') + +# Метод последовательного вычитания (классический) --> GCD2 +start2 = time.time() +alg_ex_1.gcd2(10000000, 90) +delta2 = (time.time() - start2) +print(f'Delta GCD2 (Classic Euclidean algorithm) = {delta2:.{10}}') + +if delta1 < delta2: + print(f'\nGCD1 faster than GCD2 by {round(delta2 / delta1)} times!!!') +else: + print(f'\nGCD2 faster than GCD1 by {round(delta1 / delta2)} times!!!') + +sys.stdout = orig_stdout +f.close() \ No newline at end of file diff --git a/ex1_01_module_time_output.txt b/ex1_01_module_time_output.txt new file mode 100644 index 0000000..d5b62f7 --- /dev/null +++ b/ex1_01_module_time_output.txt @@ -0,0 +1,6 @@ +Tue Sep 4 02:19:57 2018 + +Delta GCD1 (Recursion realization of Euclidean algorithm) = 3.337860107e-06 +Delta GCD2 (Classic Euclidean algorithm) = 0.009662866592 + +GCD1 faster than GCD2 by 2895 times!!! diff --git a/ex1_02_calc_delta_with_timeit.py b/ex1_02_calc_delta_with_timeit.py new file mode 100644 index 0000000..d83027f --- /dev/null +++ b/ex1_02_calc_delta_with_timeit.py @@ -0,0 +1,29 @@ +from alg_ex_1 import gcd1, gcd2 +import timeit +import sys +import time + +orig_stdout = sys.stdout +f = open('ex1_02_module_timeit_output.txt', 'w') +sys.stdout = f + +print(f'{time.ctime(time.time())}\n') + +# С модулем timeit расчет времени работы алгоритма идёт очень медленно!!! + +gcd1_t = timeit.timeit("gcd1(10000000, 9000)", setup="from __main__ import gcd1") +gcd2_t = timeit.timeit("gcd2(10000000, 9000)", setup="from __main__ import gcd2") + +print(f'Delta GCD1 (Recursion realization of Euclidean algorithm) = \ +{gcd1_t}') +print(f'Delta GCD2 (Classic Euclidean algorithm) = \ +{gcd2_t}') + + +if gcd1_t < gcd2_t: + print(f'\nGCD1 faster than GCD2 by {round(gcd2_t / gcd1_t)} times!!!') +else: + print(f'\nGCD2 faster than GCD1 by {round(gcd1_t / gcd2_t)} times!!!') + +sys.stdout = orig_stdout +f.close() \ No newline at end of file diff --git a/ex1_02_module_timeit_output.txt b/ex1_02_module_timeit_output.txt new file mode 100644 index 0000000..4a31cac --- /dev/null +++ b/ex1_02_module_timeit_output.txt @@ -0,0 +1,6 @@ +Tue Sep 4 02:13:23 2018 + +Delta GCD1 (Recursion realization of Euclidean algorithm) = 0.4171991210023407 +Delta GCD2 (Classic Euclidean algorithm) = 74.67888574000244 + +GCD1 faster than GCD2 by 179 times!!! diff --git a/ex1_03_cProfile_output.txt b/ex1_03_cProfile_output.txt new file mode 100644 index 0000000..5ff0cb8 --- /dev/null +++ b/ex1_03_cProfile_output.txt @@ -0,0 +1,30 @@ +Tue Sep 4 02:19:04 2018 + +Recursion realization of Euclidean algorithm: + + 7 function calls (5 primitive calls) in 0.000 seconds + + Ordered by: standard name + + ncalls tottime percall cumtime percall filename:lineno(function) + 1 0.000 0.000 0.000 0.000 :1() + 3/1 0.000 0.000 0.000 0.000 alg_ex_1.py:6(gcd1) + 1 0.000 0.000 0.000 0.000 ex1_03_calc_delta_with_cProfile.py:14(main_gcd1) + 1 0.000 0.000 0.000 0.000 {built-in method builtins.exec} + 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} + + +Classic realization of Euclidean algorithm: + + 5 function calls in 0.011 seconds + + Ordered by: standard name + + ncalls tottime percall cumtime percall filename:lineno(function) + 1 0.000 0.000 0.011 0.011 :1() + 1 0.011 0.011 0.011 0.011 alg_ex_1.py:22(gcd2) + 1 0.000 0.000 0.011 0.011 ex1_03_calc_delta_with_cProfile.py:17(main_gcd2) + 1 0.000 0.000 0.011 0.011 {built-in method builtins.exec} + 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} + + diff --git a/ex1_03_calc_delta_with_cProfile.py b/ex1_03_calc_delta_with_cProfile.py new file mode 100644 index 0000000..64cf6dc --- /dev/null +++ b/ex1_03_calc_delta_with_cProfile.py @@ -0,0 +1,26 @@ +import cProfile +from alg_ex_1 import gcd1, gcd2 +import sys +import time + +orig_stdout = sys.stdout +f = open('ex1_03_cProfile_output.txt', 'w') +sys.stdout = f + +print(f'{time.ctime(time.time())}\n') + +# При запуске вывод программы автоматически сохранятся в cProfile_output.txt + +def main_gcd1(): + gcd1_t = gcd1(10000000, 90) + +def main_gcd2(): + gcd1_t = gcd2(10000000, 90) + +print('Recursion realization of Euclidean algorithm:\n') +cProfile.run('main_gcd1()') +print('Classic realization of Euclidean algorithm:\n') +cProfile.run('main_gcd2()') + +sys.stdout = orig_stdout +f.close() \ No newline at end of file diff --git a/ex2_01_calc_delta_with_time.py b/ex2_01_calc_delta_with_time.py new file mode 100644 index 0000000..3d61c88 --- /dev/null +++ b/ex2_01_calc_delta_with_time.py @@ -0,0 +1,29 @@ +import alg_ex_2 +import sys +import time + +orig_stdout = sys.stdout +f = open('ex2_01_module_time_output.txt', 'w') +sys.stdout = f + +print(f'{time.ctime(time.time())}\n') + +# Решето Эратосфена +start1 = time.time() +alg_ex_2.Eratosthenes(100000) +delta1 = (time.time() - start1) +print(f'Eratosthenes(n) algorithm delta = {delta1:.{10}}') + +# Решето Аткина +start2 = time.time() +alg_ex_2.Atkin(100000) +delta2 = (time.time() - start2) +print(f'Atkin(nmax) algorithm delta = {delta2:.{10}}') + +if delta1 < delta2: + print(f'\nEratosthenes algorithm faster than Atkin algorithm by {round(delta2 / delta1)} times!!!') +else: + print(f'\nAtkin algorithm faster than Eratosthenes algorithm by {round(delta1 / delta2)} times!!!') + +sys.stdout = orig_stdout +f.close() diff --git a/ex2_01_module_time_output.txt b/ex2_01_module_time_output.txt new file mode 100644 index 0000000..642fc2c --- /dev/null +++ b/ex2_01_module_time_output.txt @@ -0,0 +1,6 @@ +Tue Sep 4 01:37:23 2018 + +Eratosthenes(n) algorithm delta = 0.605956316 +Atkin(nmax) algorithm delta = 2.59232831 + +Eratosthenes algorithm faster than Atkin algorithm by 4 times!!! diff --git a/ex2_02_calc_delta_with_timeit.py b/ex2_02_calc_delta_with_timeit.py new file mode 100644 index 0000000..00169e6 --- /dev/null +++ b/ex2_02_calc_delta_with_timeit.py @@ -0,0 +1,29 @@ +from alg_ex_2 import Eratosthenes, Atkin +import timeit +import sys +import time + +orig_stdout = sys.stdout +f = open('ex2_02_module_timeit_output.txt', 'w') +sys.stdout = f + +print(f'{time.ctime(time.time())}\n') + +# С модулем timeit расчет времени работы алгоритма идёт очень медленно!!! + +eratosthenes_t = timeit.timeit("Eratosthenes(30)", setup="from __main__ import Eratosthenes") +atkin_t = timeit.timeit("Atkin(30)", setup="from __main__ import Atkin") + +print(f'Delta Eratosthenes algorithm = \ +{eratosthenes_t}') +print(f'Delta Atkin algorithm = \ +{atkin_t}') + + +if eratosthenes_t < atkin_t: + print(f'\nEratosthenes algorithm faster than Atkin algorithm by {round(atkin_t / eratosthenes_t)} times!!!') +else: + print(f'\nAtkin algorithm faster than Eratosthenes algorithm by {round(eratosthenes_t / atkin_t)} times!!!') + +sys.stdout = orig_stdout +f.close() diff --git a/ex2_02_module_timeit_output.txt b/ex2_02_module_timeit_output.txt new file mode 100644 index 0000000..6fdf95f --- /dev/null +++ b/ex2_02_module_timeit_output.txt @@ -0,0 +1,6 @@ +Tue Sep 4 02:00:54 2018 + +Delta Eratosthenes algorithm = 7.828766642996925 +Delta Atkin algorithm = 59.988633288994606 + +Eratosthenes algorithm faster than Atkin algorithm by 8 times!!! diff --git a/ex2_03_cProfile_output.txt b/ex2_03_cProfile_output.txt new file mode 100644 index 0000000..ad9b697 --- /dev/null +++ b/ex2_03_cProfile_output.txt @@ -0,0 +1,34 @@ +Tue Sep 4 02:10:31 2018 + +Eratosthenes algorithm: + + 9597 function calls in 0.050 seconds + + Ordered by: standard name + + ncalls tottime percall cumtime percall filename:lineno(function) + 1 0.000 0.000 0.050 0.050 :1() + 1 0.049 0.049 0.050 0.050 alg_ex_2.py:5(Eratosthenes) + 1 0.000 0.000 0.050 0.050 ex2_03_calc_delta_with_cProfile.py:14(main_eratosthenes) + 1 0.000 0.000 0.050 0.050 {built-in method builtins.exec} + 9592 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} + 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} + + +Atkin algorithm: + + 9916 function calls in 0.276 seconds + + Ordered by: standard name + + ncalls tottime percall cumtime percall filename:lineno(function) + 1 0.000 0.000 0.276 0.276 :1() + 1 0.259 0.259 0.274 0.274 alg_ex_2.py:34(Atkin) + 1 0.014 0.014 0.014 0.014 alg_ex_2.py:38() + 1 0.002 0.002 0.276 0.276 ex2_03_calc_delta_with_cProfile.py:17(main_atkin) + 1 0.000 0.000 0.276 0.276 {built-in method builtins.exec} + 318 0.000 0.000 0.000 0.000 {built-in method math.sqrt} + 9592 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} + 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} + + diff --git a/ex2_03_calc_delta_with_cProfile.py b/ex2_03_calc_delta_with_cProfile.py new file mode 100644 index 0000000..c1241ab --- /dev/null +++ b/ex2_03_calc_delta_with_cProfile.py @@ -0,0 +1,26 @@ +import cProfile +from alg_ex_2 import Eratosthenes, Atkin +import sys +import time + +orig_stdout = sys.stdout +f = open('ex2_03_cProfile_output.txt', 'w') +sys.stdout = f + +print(f'{time.ctime(time.time())}\n') + +# При запуске программы вывод автоматически сохранятся в ex2_03_cProfile_output.txt + +def main_eratosthenes(): + eratosthenes_t = Eratosthenes(100000) + +def main_atkin(): + atkin_t = Atkin(100000) + +print('Eratosthenes algorithm:\n') +cProfile.run('main_eratosthenes()') +print('Atkin algorithm:\n') +cProfile.run('main_atkin()') + +sys.stdout = orig_stdout +f.close() \ No newline at end of file