Counting How Many Factors An Integer Has
Solution 1:
With the line for i in range(1,integer+1):
you are looping through all the numbers between 1 and your integer, including 1 and your integer, which are of course factors.
So for example if integer = 5
, you'd loop over 1, 2, 3, 4, and 5. Out of these 1 and 5 are both of course factors of 5.
You could edit the line to for i in range(2,integer):
to fix the error. The resulting code would look like this:
defnum_factors(integer):
result = 0for i inrange(2,integer):
if integer%i == 0:
result +=1return result
print(num_factors(5))
print(num_factors(6))
print(num_factors(97))
print(num_factors(105))
print(num_factors(999))
Though as someone in the comments suggested, you could reduce the search space even more.
Solution 2:
sympy provides this function to find prime factors.
>>>from sympy.ntheory import factorint>>>factorint(6008) # 6008 = (2**3) * (751**1)
{2: 3, 751: 1}
Solution 3:
The issue is that you are counting division by 1 and the test integer itself.
You either need to subtract 2 or skip 1
and integer
to get what you want as the desired output:
def num_factors(integer):
result=0for i inrange(2,integer): # skips 1and integer...
if integer%i ==0:
result+=1returnresult
And even better is to realize that for every x * y
that is a factor of integer
we only need to find one of them (ie, 16
has 2
,4
,and 8
as factors. Count 2 twice (2 x 8=16) and 4 once (4 x 4=16)) And since one will be less than or equal to the square root of integer
just loop to the square root of integer
and increment by 2 instead of by 1 and only make a fraction of the tests (and make the result 1000's of times faster):
def num_factors(integer):
result=0
stop=int(float(integer)**0.5)
for i inrange(2,stop+1):
if integer%i ==0:
result+=2
if stop*stop==integer: result-=1returnresultfor x in (5,6,97,105,999):
print(f'{x}: {num_factors(x)}')
Prints:
5: 06: 297: 0105: 6999: 6
BTW: It is, in fact, customary to count 1
and the integer itself as factors. So all these results should be +2 and your original solution was actually correct. To make the solutions above correct, just start with result=2
Solution 4:
I would do it this way:
def num_factors(integer):
for i in range(1, integer, 1):
if integer % i == 0:
print(i)
print(num_factors(5))
print(num_factors(6))
print(num_factors(97))
print(num_factors(105))
print(num_factors(999))
Solution 5:
try this :
num_factors=lambda integer : len([e for e in range(1,integer) ifinteger%e==0 and e not in [1,integer]])
print(num_factors(5))
print(num_factors(6))
print(num_factors(97))
print(num_factors(105))
print(num_factors(999))
Post a Comment for "Counting How Many Factors An Integer Has"