speed up prime number generating? [duplicate] - python

This question already has answers here:
Fastest way to list all primes below N
(39 answers)
Closed 3 years ago.
This program generates prime numbers . It works well but I want to speed it up as it takes quite a while for generating the all the prime numbers
#!/usr/bin/python
#intgr = int(raw_input ("Please enter your number: "))
intgr = 50000
for i in range (2, intgr+1):
j = 2
while j<i:
if (i%j) == 0:
break
j += 1
if j == i:
#print "prime", i
pass #print "prime", i
print "done"
it takes about 15 seconds to run right now i would like to decrease that time.

Generating prime numbers is inherently slow. The algorithm you implemented is known as Trial Division and is one of the slowest ways to generate primes. There are other algorithms which are much faster, for example the Sieve of Eratosthenes. I suggest you do some more research about better algorithms.

Related

Python number limitation on calculation(not on float)

I'm doing codeforces and found in huge number, my simple code started to make some bugs.
n = int(input())
for i in range(n):
candies = sum(map(int,input().split()))
if candies % 2 == 0:
print(int(candies/2))
else:
print(int((candies-1)/2))
when I put
1
9547116602436426 8316250877914575 2981260158260522
I expected to see '10422313819305761' but what I get is '10422313819305760'.
But in other small numbers, of all combination in odd and even numbers, it worked very well. I used math.floor instead of if as well, but it gave me same answer.
Is there any limit on huge numbers in python?

Understanding elegant prime number tester

I'm new to Python and testing myself with some questions. One that came up was to test whether a user inputted number was prime or not. Easy enough, but one person came up with a single line of code as a solution.
import math
num = int(input("Enter a number greater than 2 "))
if sum([True if num%factor == 0 else False for factor in ([2] + list(range(3,int(math.sqrt(num)),2)))]):
print("Number is composite")
else:
print("Number is prime")
I understand part of it: the if statement is True if (number/iterations) gives a remainder of 0, else False, where the only iterations that need to be checked are 2 -> sqrt(number) skipping all even numbers.
However, I can't work out how to sum operator at the start of the if statement works. I assume it operates on the True(1)/False(0) statements, but how does this interaction play out and how does it affect the if/else statements?

Compute the factorial of n using range with two parameters [duplicate]

This question already has answers here:
Python "if" statement syntax error
(5 answers)
Closed 5 years ago.
I am trying to compute the factorial of n using for loop and an accumulator. I am having trouble with the range command and its two parameters - start and end. I am getting invalid syntax error. Here's the code:
# factorial.py
# Program to compute the factorial of a number
# Illustrates for loop with an accumulator
def main():
n = int(input("Please enter a whole number: "))
fact = 1
for factor in range(1, (n + 1))
fact = fact * factor
print("The factorial of", n, "is", fact)
main()
Where's the problem?
I am using Python 3.6.
You simply forgot a : after your range function since it is a for loop ^.^

Being told I have an infinite loop, but I'm unsure how to fix it. (Python Coding Course)

I'm currently in a python coding class and this is an assignment. I apparently have an infinite loop somewhere in my code, yet I can't seem to find it.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
# At this point the program should take your now factorial and give you the fibonacci sequence
# takes your factorial and makes it the fibonacci
nterms = factorial
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
I've used both the debugging tool and attempted to find the problem myself by running the programming and attempting various break sequences but I'm just not grasping it.
There is no infinite loop in your code, both loops will finish in finite time. What is happening is that your teacher, without looking at your code, has discovered that the finite time is very, very long and mistaken this for an infinite loop.
The reason it's taking so long is that you have misunderstood the question - "I was asked to make a program that took an integer and gave me said factorial of an integer. Then give the Fibonacci sequence of the integer" - means find the factorial and Fibonacci sequence of the same integer rather than feeding the first result into the second. Simply replace the line nterms = factorial with the line nterms = num to fix the problem.
(See comments on question for additional information used in this answer)
First, you already know what a loop is and how it works. You should review the loop in your code and make sure any variable used is defined. Since this is an assignment, this is the best I can do for you, to be honest your problem is already solved.
Maybe try enclosing your code in a function with arguments/input-variables, this way your code might run smoother and better. Hope this helps.

Python Printing Prime Numbers

TASK : Write a program that prints out all the primes below 10,000.
Hint: you will need to use % which gives the remainder of a division operation.
So x=11%5 would give 1 as 11/5=2 remainder 1
I FOUND THIS CODE , can someone add annotations next to all the lines explaining what is happening.I totally don't understand this code.
numbers=[]
for i in range(0,10001):
numbers.append(" ") #We just put spaces in each box for now
numbers[0]="X"
numbers[1]="X"
firstFree=2
while firstFree<10001:
multiple=firstFree*2
while multiple<10001: #Mark all multiples of firstFree as X
numbers[multiple]='X'
multiple=multiple+firstFree
firstFree=firstFree+1
while firstFree<10000 and numbers[firstFree]=='X':
firstFree=firstFree+1
for i in range(0,10001):
if(numbers[i]!='X'):
print(i)
As you have been told, you should not learn that way. Plus, in my humble opinion, this code you have found is extremely ugly and hard to read.
This is beter example.
#Main loop, this is self explanatory.
for dividend in range(2, 10000):
#This loops through all divisors available.
for divisor in range(2, dividend):
#Check against reminder of division.
if dividend % divisor == 0:
#Prints all composites of prime number that failed against check.
print('{} equals {} * {}'.format(dividend, divisor, dividend//divisor))
#Breakes second loop.
break
#Find answer for this thing yourself. It is interesting.
else:
#Enters here when have not found division factor.
print('{} is one of the prime numbers.'.format(dividend))
Read tons of tutorials, train and learn.

Categories