0

I am trying to output numbers that have only 3 factors. I wrote a code to output all the factors, but can't get it to output the number that has 3 factors. For instance, if a list has 1,5,6,7 .. it Will output 6 .. since 6 has three factors : 1, 2 and 3 .. (itself) not being a factor. This is what I have till now:

def factors(n):
    result = []

    for i in range(1, n + 1):
        if n % i == 0:
            result.append(i)

    return result
J Doe
  • 317
  • 1
  • 4
  • 12
  • The usual definition of "factor" implies that any positive integer is indeed a factor of itself. You would be better off saying that you want to output positive integers that have 4 factors, such as 6 (whose factors are 1,2,3, and 6) and 8 (whose factors are 1,2,4, and 8). Such a number is either a product of two distinct primes (such as 6==2*3) or the cube of a prime (such as 8==2**3). – Rory Daulton Jan 21 '18 at 22:51
  • 2
    @ImportanceOfBeingErnest, I'm not sure why you think a question about "all factors" is a duplicate of a question about "prime factors" – SergGr Jan 21 '18 at 23:03
  • So have you tried evaluating the length of your result list? You could, for instance, wrap that function in a loop that goes through a list of integers and only prints them out if `len(result)=3` – neophlegm Jan 22 '18 at 00:10

1 Answers1

2

A simple example is as follows, where you loop through some numbers and test each to see if it has exactly three factors. It won't be particularly efficient though...

#This will be your answers
results=[]
#Whatever you want your upper bound to be
highestValue=100

#Loop through up to your highest value
for eachVal in range(highestValue):
    #If the length of the factor list is exactly 3, store the answer
    if len(factors(eachVal))==3:
        results.append(eachVal)

print(results)

EDIT: This of course, uses your "factors" function from your code snippet, so make sure it's either in the same module or you import it first.

neophlegm
  • 375
  • 1
  • 13