Looped Nesting -- Factorising
I am trying to write a program that takes a user input, limit and prints a table to visualise all the factors of each integer ranging from 1 to the limit. Each row represents an in
Solution 1:
You should use the variable i
or limit
in your inner loop as well. So you will generate a limit * limit
output. Also you have to iterate until limit + 1
to get full limit
rows.
A detailed version:
# get a maximim number and cast it to int
limit = int(input('Maximum number to factorise: '))
# prints a header [1; limit]
print " " + "".join(["%3d" % i for i in xrange(1, limit + 1)])
# outer loop: [1; limit]
for i in range(1, limit + 1):
line = '%2d ' % i # format string row number
# inner loop: [1; limit]!
for j in range (1, i + 1): # you can also set limit + 1
if i % j: # if i % != 0
line += '- '
else:
line += '* '
print(line)
Generates:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 *
2 * *
3 * - *
4 * * - *
5 * - - - *
6 * * * - - *
7 * - - - - - *
8 * * - * - - - *
9 * - * - - - - - *
10 * * - - * - - - - *
11 * - - - - - - - - - *
12 * * * * - * - - - - - *
13 * - - - - - - - - - - - *
14 * * - - - - * - - - - - - *
15 * - * - * - - - - - - - - - *
16 * * - * - - - * - - - - - - - *
17 * - - - - - - - - - - - - - - - *
18 * * * - - * - - * - - - - - - - - *
19 * - - - - - - - - - - - - - - - - - *
20 * * - * * - - - - * - - - - - - - - - *
Solution 2:
You want something like:
limit = input('Maximum number to factorise: ')
for i in range(1,int(limit)):
line = '{:2}:'.format(i)
for j in range (1,11):
if i % j == 0:
line += "{:4}".format('0')
else:
line += "{:4}".format('-')
print(line)
Post a Comment for "Looped Nesting -- Factorising"