Numbers With 3 Divisors
August 30, 2019
I saw this question on Stack Overflow a few days ago; it’s a well-known problem in number theory:
For a given number n, how many numbers less than n have exactly 3 divisors?
Your task is to write a program that counts the numbers less than n that have exactly 3 divisors, and use it to find the result when n is one billion. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Klong version
@ProgrammingPraxis: Thanks again for the problem. Would be interesting to see the Pari/GP version of your solution. I didn’t make heads or tails of the Scheme one. Wish there was a Pari/GP version for iOS.
@bookofstevegraham: The Pari/GP version of my solution is given on the solution page: primepi(sqrt(1000000000000)).
The first line shows the number of divisors.
Tried this out on Python. Took me a while since I’m still basic. I learnt a lot from doing it. Only once I got the program to work did I realize that numbers with only 3 factors are just the squares of prime numbers, which led to me making the second, but more inefficient code.
l = list(range(1, int(input(“Choose a number :”))))
b = [] #Stores a number every time it’s modulo is 0
d = [] #The numbers with 3 factors
for i in l : #i is each term in l
a = list(range(1, int(1 + i))) #All values from 1 up to i
for c in a :
if i % c == 0 :
b.append(i)
if not len(b) == 3 :
b = [] #Clears the list for reuse
if len(b) == 3 :
d += b
b = [] #Clears the list for reuse
d = set(d) #Gets rid of duplicates
d = list(d)
print(d)
l = list(range(1, int(input(“Choose a number :”))))
print(“”)
b=[]
c=[]
for x in l :
y = x ** (1/2)
a = y
if y % 1 == 0 :
while a > 0 :
if y % a == 0 :
b.append(x)
a -= 1
if len(b) == 2 :
c.append(b)
else :
b = []
else :
continue
print(c)