Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions alg_ex_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Алгоритм Евклида. Нахождение "Наибольшего Общего Делителя (НОД)"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

На дом такую задачу я не задавал. Почему вы решили взять её. Но всё равно дочитаю до конца.


# Рекурсивная реализация алгоритма Евклида. --> 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))

75 changes: 75 additions & 0 deletions alg_ex_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import math

# Решето Эратосфена
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Решето Эратосфена из урока. Хорошо. Но ответ про i-е простое число функция не выдаёт.


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):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ещё одно решето. Класс. И работает. Но проблема та же. Прошу сказать мне 5-е простое число и вместо 11 получаю список [2, 3, 5].

"""
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(((!')
29 changes: 29 additions & 0 deletions ex1_01_calc_delta_with_time.py
Original file line number Diff line number Diff line change
@@ -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()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Знакомый вариант для замера времени )))

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()
6 changes: 6 additions & 0 deletions ex1_01_module_time_output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Tue Sep 4 02:19:57 2018
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Представляю как у вас кипела работа ночью )))


Delta GCD1 (Recursion realization of Euclidean algorithm) = 3.337860107e-06
Delta GCD2 (Classic Euclidean algorithm) = 0.009662866592

GCD1 faster than GCD2 by 2895 times!!!
29 changes: 29 additions & 0 deletions ex1_02_calc_delta_with_timeit.py
Original file line number Diff line number Diff line change
@@ -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 расчет времени работы алгоритма идёт очень медленно!!!
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ещё бы. Ведь модуль запускает алгоритм 1000000 раз.


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()
6 changes: 6 additions & 0 deletions ex1_02_module_timeit_output.txt
Original file line number Diff line number Diff line change
@@ -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!!!
30 changes: 30 additions & 0 deletions ex1_03_cProfile_output.txt
Original file line number Diff line number Diff line change
@@ -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 <string>:1(<module>)
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 <string>:1(<module>)
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}


26 changes: 26 additions & 0 deletions ex1_03_calc_delta_with_cProfile.py
Original file line number Diff line number Diff line change
@@ -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()
29 changes: 29 additions & 0 deletions ex2_01_calc_delta_with_time.py
Original file line number Diff line number Diff line change
@@ -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()
6 changes: 6 additions & 0 deletions ex2_01_module_time_output.txt
Original file line number Diff line number Diff line change
@@ -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!!!
29 changes: 29 additions & 0 deletions ex2_02_calc_delta_with_timeit.py
Original file line number Diff line number Diff line change
@@ -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()
6 changes: 6 additions & 0 deletions ex2_02_module_timeit_output.txt
Original file line number Diff line number Diff line change
@@ -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!!!
34 changes: 34 additions & 0 deletions ex2_03_cProfile_output.txt
Original file line number Diff line number Diff line change
@@ -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 <string>:1(<module>)
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 <string>:1(<module>)
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(<listcomp>)
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}


26 changes: 26 additions & 0 deletions ex2_03_calc_delta_with_cProfile.py
Original file line number Diff line number Diff line change
@@ -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()