Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help! Function doesn't run
#1
Hi everyone! I am trying to find 1000th prime number with this function, there is no any errors but it doesn't run and I don't know why. Can you help me?
import sys


def thousandprime():
    for i in range(sys.maxsize**10):
        primes = []
        if i % 2 != 0 and i % 3 != 0 and i % 5 != 0 and i % 7 != 0:
            primes.append(i)
        elif len(primes) == 1000:
            print(primes[-1])
            return 
           
thousandprime()        
Reply
#2
The function actually does run, but it gets stuck in a nearly endless loop. That is because you reset primes to an empty list in each iteration.
Reply
#3
Also, your for i in range(sys.maxsize**10) is making a loop from 0 to 2 to the 63rd power minus 1, and that to the 10th power. That's a really big number. Like, 4.45 x 10^189. That loop might take a little while to run...
Reply
#4
(Jul-07-2020, 11:36 AM)jefsummers Wrote: Also, your for i in range(sys.maxsize**10) is making a loop from 0 to 2 to the 63rd power minus 1, and that to the 10th power. That's a really big number. Like, 4.45 x 10^189. That loop might take a little while to run...

I see and thank you, what do you suggest for range interval, how can I rearrange it?
Reply
#5
Have you considered using the sieve of Eratosthenes?
Reply
#6
Agree there are better ways, such as that suggested by ndc85430. However, following the method you created -
You don't need a maximum range as outer loop. Just test to see if the len(primes) is 1000 and quit when it is.
You also need to check if the mod of each prime is 0, not just 2,3,5,7. Your routine will flag 11*13 as prime which it isn't.
Don't print from the function. As discussed in other threads, a function should return a result. The only time a function should print is if that is actually the purpose of the function (it is a function that prints data in a particular format, for example).
To make this more useful, make the function take an argument that specifies which prime. Then call it on 1000 and it gives the 1000th prime.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  string function doesn't work in script ClockPillow 3 2,331 Jul-13-2021, 02:47 PM
Last Post: deanhystad
Star NameError – function doesn't recognize imported modules Sir 4 3,416 Dec-01-2020, 06:36 AM
Last Post: Sir
  len() function, numbers doesn't work with Geany Editor Penguin827 3 2,936 May-08-2020, 04:08 AM
Last Post: buran
  why my function doesn't work cimerio 4 2,826 Jan-20-2020, 08:11 PM
Last Post: cimerio
  Doesn't work function pyautogui.typewrite() aliyevmiras 1 4,751 Dec-22-2019, 11:35 AM
Last Post: aliyevmiras
  len() function doesn't work with Geany Editor hudabaig 2 3,550 Jun-01-2018, 11:20 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020