Changing "if n % i == 0" on line 6 to "if not(n % i)" made the time drop from 4126ms to 3810ms (as the longest time).
from math import sqrt, floor def divisors(n): fact = []; for i in range(1, int(floor(sqrt(n))) + 1): if not(n % i): fact.append(i) if n / i != i: fact.append(n / i) fact.sort() return fact
- from math import sqrt, floor
- def divisors(n):
- fact = [];
- for i in range(1, int(floor(sqrt(n))) + 1):
if n % i == 0:- if not(n % i):
- fact.append(i)
- if n / i != i:
- fact.append(n / i)
- fact.sort()
- return fact
from math import sqrt, floor def divisors_check(n): fact = []; for i in range(1, int(floor(sqrt(n))) + 1): if not(n % i): fact.append(i) if n / i != i: fact.append(n / i) fact.sort() return fact test.describe( "Static Cases" ) test.it( "n = 200" ) test.assert_equals(divisors(200), [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200]) test.it( "n = 560") test.assert_equals(divisors(560), [1, 2, 4, 5, 7, 8, 10, 14, 16, 20, 28, 35, 40, 56, 70, 80, 112, 140, 280, 560]) test.it("n = 755") test.assert_equals(divisors(755), [1, 5, 151, 755]) from random import randint test.describe( "Random Tests") test.it ("More than 1000 Random Tests with challenging values up to 1000000000(10e9)") for h in range(0,1000): n = randint(1000, 1000000000) result = divisors_check(n) res = divisors(n) test.it("Testing for = " + str(n)) test.assert_equals(res, result)
- from math import sqrt, floor
- def divisors_check(n):
- fact = [];
- for i in range(1, int(floor(sqrt(n))) + 1):
if n % i == 0:- if not(n % i):
- fact.append(i)
- if n / i != i:
- fact.append(n / i)
- fact.sort()
- return fact
- test.describe( "Static Cases" )
- test.it( "n = 200" )
- test.assert_equals(divisors(200), [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200])
- test.it( "n = 560")
- test.assert_equals(divisors(560), [1, 2, 4, 5, 7, 8, 10, 14, 16, 20, 28, 35, 40, 56, 70, 80, 112, 140, 280, 560])
- test.it("n = 755")
- test.assert_equals(divisors(755), [1, 5, 151, 755])
- from random import randint
- test.describe( "Random Tests")
- test.it ("More than 1000 Random Tests with challenging values up to 1000000000(10e9)")
- for h in range(0,1000):
- n = randint(1000, 1000000000)
- result = divisors_check(n)
- res = divisors(n)
- test.it("Testing for = " + str(n))
- test.assert_equals(res, result)