Skip to content

Commit 0ec2419

Browse files
committed
add exercise 4
1 parent fb413e5 commit 0ec2419

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

exercises_4.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
'''
5+
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
6+
7+
(If you don’t know what a divisor is, it is a number that divides evenly into another number.
8+
For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
9+
'''
10+
11+
n = raw_input('Please input a number: ')
12+
n = int(n)
13+
14+
# The simplest solution
15+
res = []
16+
for i in xrange(2, n):
17+
if n % i == 0:
18+
res.append(i)
19+
20+
res.append(1)
21+
res.append(n)
22+
23+
res.sort()
24+
25+
print 'The following are divisors of your input number: '
26+
print res
27+
28+
# A more efficient solution
29+
30+
from math import sqrt
31+
32+
x = int(sqrt(n))
33+
34+
res2 = []
35+
for i in xrange(2, x):
36+
if n % i == 0:
37+
res2.append(i)
38+
res2.append(n/i)
39+
40+
if n == x * x:
41+
res.append(x)
42+
43+
res2.append(1)
44+
res2.append(n)
45+
46+
res2.sort()
47+
48+
print 'The following are divisors of your input number calculated by another way: '
49+
print res2

0 commit comments

Comments
 (0)