I want to show n and the number of factors (excluding 1 and itself) of n. like this example
n factor
1 0
2 0
3 0
4 1
5 0
6 2
7 0
8 2
9 1
10 2
So I wrote the code like this my code
n = int(input('Enter the number: '))
factor = 0
for a in range(1, n 1):
if n % a == 0:
factor = 1
fctr = factor - 2
print("%d" '\t' "]" %(a, fctr))
I don't know why it doesn't work. I've been thinking about it for two days, but I still don't get it why it's not working. Did I write "for" incorrectly?
CodePudding user response:
If you want number of factors for all the numbers from 1
to n
you should write two for loops (nested one). One for iterating through numbers from 1
to n
and the other for finding numbers of factors for ath
number.
So this solves the problem -
n = int(input('Enter the number: '))
for a in range(1, n 1):
factor = 0
for b in range(2, a):
if a % b == 0:
factor = 1
print("%d" '\t' "]" %(a, factor))
CodePudding user response:
You're doing
fctr = factor - 2
for every iteration of the loop
for a in range(1, n 1):
That would probably give you a negative value in the very beginning. Since you know you just don't want to count 1 and n why not run the loop as:
for a in range(2, n):
Based off of your example, are you trying to print the number of factors of each number from 1 to n? Because that would require another outer for loop. Right now you're only printing the number of factors of n (seen so far at every point of the loop).