Reputation: 13
Divisors: For numbers from 2 to 100, print a series of lines indicating which numbers are divisors of other numbers. For each, print out “X divides Y”, where X <= Y, and both X and Y are between 2 and 100. The first few lines will be: 2 divides 2 3 divides 3 2 divides 4 4 divides 4 5 divides 5 etc.
So far I have this
x = 2
y = 2
while y <= 100:
while y <= 100:
if y % x == 0:
print(x, 'divides', y)
y += 1
elif y % x != 0:
y += 1
Im not sure how to make it test the other values of x and y
Upvotes: 0
Views: 1182
Reputation: 4606
You can use enumerate here and cycling through the indexes prior to every item will produce the results you are trying to get
x = [*range(2, 101)]
for idx, item in enumerate(x):
for i in x[:idx +1]:
if not item % i:
print('{} divides {}'.format(i, item))
2 divides 2 3 divides 3 2 divides 4 4 divides 4 5 divides 5 2 divides 6 3 divides 6 6 divides 6 ... 99 divides 99 2 divides 100 4 divides 100 5 divides 100 10 divides 100 20 divides 100 25 divides 100 50 divides 100 100 divides 100
Upvotes: 0
Reputation: 137
This should do a work. Give it a try, if something is unclear give me a shout
x = int(input("Give the range you want to check numbers in: "))
for number in range(1,x):
for value in range(1,number+1):
if number % value == 0:
print(number, " is divided by", value)
Output for input "10":
1 is divided by 1
2 is divided by 1
2 is divided by 2
3 is divided by 1
3 is divided by 3
4 is divided by 1
4 is divided by 2
4 is divided by 4
5 is divided by 1
5 is divided by 5
6 is divided by 1
6 is divided by 2
6 is divided by 3
6 is divided by 6
7 is divided by 1
7 is divided by 7
8 is divided by 1
8 is divided by 2
8 is divided by 4
8 is divided by 8
9 is divided by 1
9 is divided by 3
9 is divided by 9
Upvotes: 0
Reputation: 39062
Here is a corrected version of your code for a smaller value of y
up to 6.
You can extend it to 100.
Explanation: The first while loop checks for y
value. For each y
value, you check for its divisors using the second while loop which runs over x
. You update x
by 1 within the inner while
loop and update y
by 1 within the outer while
loop. Comment below if something is unclear.
Problems with your code: You were using two while
loops just for y
, one of which was redundant. Moreover, you were not incrementing x
as you clearly pointed out in your question. Your elif
was also not required because you were incrementing y
in both the cases.
y = 2
while y <= 6: # Replace 6 by 100 here
x = 2 # Reset x to 2 for every y value because you count divisors from 2
while x <= y:
if y % x == 0:
print(x, 'divides', y)
x += 1
y += 1
Output
2 divides 2
3 divides 3
2 divides 4
4 divides 4
5 divides 5
2 divides 6
3 divides 6
6 divides 6
Upvotes: 1