I'm pretty new to python and I spent a couple hours on a simple project that involves prime numbers. I need to interpret a timer to count the delay of how long it takes to find x amount of prime numbers and give me back that delay in the form of a message box. Here is what I have so far for the project and it works perfectly fine.
import time
import ctypes
lower = 1
upper = 25000000
z = 1
while z < 1000:
if z == 100:
break
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
z += 1
print(z, ": ", num)
As far I understood, you want to calculate how much time you need to calculate z number of prime number.
You can simply start a timer at the beginning of the program and subtract it at the end.
import time
def is_prime(x):
if x%2 == 0:
return False
for i in range(3, x, 2):
if x%i == 0:
return False
return True
start_time = time.time()
z = 1
i=3
while True:
if z == 3000:
break
if is_prime(i):
z += 1
i += 1
delay = time.time() - start_time
print('Delay: ', delay)
Delay: 1.3431673049926758
Related
I'm a beginner in Python and I'm practicing to code this problem I saw. Next prime is needed, but there are limitations on the input. I have searched for similar questions, but my code is still not working. Hope you can help. Thank you!
The problem I get is when I enter 32, the results show 33 when the next prime is 37...
Here's my code so far.
num = int(input("Enter a positive number:"))
import math
def nextprime(n):
if n < 0:
raise ValueError
for next in range(n + 1, n +200):
if next > 1:
for i in range(2, next):
if (next % i) == 0:
break
else:
return next
In your code when you arrive to a number that reminder is not zero you return that number. You need a flag for every number this flag is True if can be divide flag convert to False for the first number that flag not convert to false return that number like below.
Don't use next because this is a builtin function.
Try this: (I don't improve your code)
def nextprime(n):
if n < 0:
raise ValueError
for i in range(n + 1, n +200):
if i > 1:
pr = True
for j in range(2, i):
if (i % j) == 0:
pr = False
break
if pr:
return i
return 'not found'
You can also try this code, write function to check that a number is prime or not like def is_prime then for number of larger that you input num find min number next. (this answer from this thread.)
def is_prime(x):
return all(x % i for i in range(2, x))
def next_prime(x):
return min([a for a in range(x+1, 2*x) if is_prime(a)])
print(next_prime(32))
You can also use sympy like below: (this answer from this thread.)
from sympy import *
nextprime(32)
def next_prime(n):
while True:
n=n+1
for i in range (2,int(n/2)):
if n%i==0:
break
else:
return n
print(next_prime(67))
Few off-topic tips:
as user1740577 mentioned, don't use next as a variable name
refrain from using eval when possible, it's okay here, but in real project this will lead to big no-no.
Place imports at the very top of your script
Consider using variable names i and j only for iterations.
For duplicate except blocks use (Error, Error)
As for solution to your problem, with some adjustments, if you don't mind
def next_prime(n: int) -> int:
if n < 0:
raise ValueError('Negative numbers can not be primes')
# Base case
if n <= 1:
return 2
# For i as every odd number between n + 1 and n + 200
for i in range(n + 1 + (n % 2), n + 200, 2):
# For every odd number from 3 to i (3 because we covered base case)
for j in range(3, i, 2):
# If remained is equals to 0
if not i % j:
# break current loop
break
# If loop j didn't break [nobreak: ]
else:
return i
raise RuntimeError('Failed to compute next prime number :c')
def main():
while True:
try:
num = int(input('Enter positive number: '))
print(f'Next prime is: {next_prime(num)}')
break
except ValueError:
print('Please enter a positive integer!')
if __name__ == '__main__':
main()
Made some speed improvements to the code from #rajendra-kumbar:
#!/usr/bin/env python
import sys
import time
import math
def next_prime(number):
if number < 0:
raise ValueError('Negative numbers can not be primes')
# Base case
if number <= 1:
return 2
# if even go back 1
if number % 2 == 0:
number -= 1
while True:
# only odds
number += 2
#only need to check up to and including the sqrt
max_check = int(math.sqrt(number))+2
# don't need to check even numbers
for divider in range(3, max_check, 2):
# if 'divider' divides 'number', then 'number' is not prime
if number % divider == 0:
break
# if the for loop didn't break, then 'number' is prime
else:
return number
if __name__ == '__main__':
number = int(sys.argv[1].strip())
t0 = time.time()
print('{0:d} is the next prime from {1:d}'.format(next_prime(number), number))
run_time = time.time() - t0
print('run_time = {0:.8f}'.format(run_time))
it is about twice as fast
You can try something like simple:
def is_prime(number:int):
check = 0
for i in range(2,number):
if number % i == 0:
check += 1
if check == 0:
return True
else:
return False
def next_prime(value):
check = value + 1
while is_prime(check) is False:
check += 1
return check
value = int(input("Insert the number: "))
print(next_prime(value))
I'm a new at programming, I like solving this euler questions and I know there are solutions for this problem but it's not about the problem at all actually.
So, i managed to create a working function for finding example: 33. triangular number. It works but i couldn't manage to properly desing my while loop. I wanted to make it like, it starts from first triangular checks it's divisors make list of it's divisors, checks the length of the divisors, because problem wants "What is the value of the first triangle number to have over five hundred divisors?" . But i never managed to work the while loop. Thank you for reading.
nums = [1]
triangles = [1]
divisors = []
def triangularcreator(x):
if x == 1:
return 1
n = 1
sum = 0
while n!=0:
n += 1
nums.append(n)
for i in range(len(nums)):
sum += nums[i]
triangles.append(sum)
sum = 0
if x == len(triangles):
n = 0
return triangles[-1]
counter = 1
while True:
for i in range(1, triangularcreator(counter) + 1):
if triangularcreator(counter) % i == 0:
divisors.append(i)
if len(divisors) == 500:
print(triangularcreator(counter))
break
counter +=1
divisors.clear()
You should try to change a few things, starting with calculating just once the value of triangularcreator(counter) and assigning this value to a variable that you can use in different points of your code.
Second, you create a loop which will be calculate always triangularcreator(1). At the end of each iteration you increase the value of counter+=1, but then at the beginign of the new iteration you assignt it again value 1, so it will not progress as you expect. Try this few things:
counter = 1
while True:
triangle = triangularcreator(counter)
for i in range(1, triangle + 1):
if triangle % i == 0:
divisors.append(i)
if len(divisors) == 500:
print(triangle )
break
counter +=1
Also these two arrays nums = [1], triangles = [1] should be declared and initialized inside the def triangularcreator. Otherwise you would be appending elements in each iteration
Edit: I believe it is better to give you my own answer to the problem, since you are doing some expensive operations which will make code to run for a long time. Try this solution:
import numpy as np
factor_num = 0
n = 0
def factors(n):
cnt = 0
# You dont need to iterate through all the numbers from 1 to n
# Just to the sqrt, and multiply by two.
for i in range(1,int(np.sqrt(n)+1)):
if n % i == 0:
cnt += 1
# If n is perfect square, it will exist a middle number
if (np.sqrt(n)).is_integer():
return (cnt*2)-1
else:
return (cnt*2)-1
while factor_num < 500:
# Here you generate the triangle, by summing all elements from 1 to n
triangle = sum(list(range(n)))
# Here you calculate the number of factors of the triangle
factor_num = factors(triangle)
n += 1
print(triangle)
Turns out that both of your while loop are infinite either in triangularcreatorin the other while loop:
nums = [1]
triangles = [1]
divisors = []
def triangularcreator(x):
if x == 1:
return 1
n = 1
sum = 0
while n:
n += 1
nums.append(n)
for i in range(len(nums)):
sum += nums[i]
triangles.append(sum)
sum = 0
if len(triangles) >= x:
return triangles[-1]
return triangles[-1]
counter = 1
while True:
check = triangularcreator(counter)
for i in range(1, check + 1):
if check % i == 0:
divisors.append(i)
if len(divisors) >= 500:
tr = triangularcreator(counter)
print(tr)
break
counter +=1
Solution
Disclaimer: This is not my solution but is #TamoghnaChowdhury, as it seems the most clean one in the web. I wanted to solve it my self but really run out of time today!
import math
def count_factors(num):
# One and itself are included now
count = 2
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
count += 2
return count
def triangle_number(num):
return (num * (num + 1) // 2)
def divisors_of_triangle_number(num):
if num % 2 == 0:
return count_factors(num // 2) * count_factors(num + 1)
else:
return count_factors((num + 1) // 2) * count_factors(num)
def factors_greater_than_triangular_number(n):
x = n
while divisors_of_triangle_number(x) <= n:
x += 1
return triangle_number(x)
print('The answer is', factors_greater_than_triangular_number(500))
I'm learning Python by doing Project Euler questions and am stuck on Problem #3.
I think I've found a solution that works, but when inserting the large number 600851475143 it just doesn't return anything. I believe that it just loads and loads cause even with 6008514 it takes 10 secs to return the answer.
# What is the largest prime factor of the number x?
import math
def isPrime(x):
try:
sqr = math.sqrt(x)
if x == 0 or x == 1:
return 0
for n in range (2 , int(sqr)+1):
if x % n == 0:
return 0
return 1
except:
return 'Give positive numbers.'
def largestPrimeFactor(x):
if isPrime(x) == 1:
return 'This number is prime.'
else:
largest = -1
mid = x/2
for n in range(2,int(mid)+1):
if isPrime(n):
if x % n == 0:
largest = n
if largest == -1:
return 'Enter numbers above 1.'
else:
return largest
print(largestPrimeFactor(600851475143))
This code should work:
import math
def isPrime(x):
try:
sqr = math.sqrt(x)
if x == 0 or x == 1:
return 0
n = 2
highest = x
while n < highest:
if x%n ==0:
return 0
highest = x/ n
n +=1
return 1
except:
return 'Give positive numbers.'
def largestPrimeFactor(x):
if isPrime(x) == 1:
return 'This number is prime.'
n = 2
highest = x
largest = 1
while n < highest:
if x%n == 0:
if isPrime(n):
largest = n
highest = x/n
n +=1
return largest
print(largestPrimeFactor(600851475143))
I made an optimization:
you check if every number is a factor of x while if for example 2 is not a factor of x for sure the maximum factor of x can be x/2. Hence if n is not a factor of x the maximum possible factor of x can just be x/n.
The code for large numbers just takes really long time, as pointed out by comments. I report other bugs.
Bug 1. Inappropriate use of try/except clause. It is recommended that try contains a single command and except catches the error. PEP8 also recommends specifying the type of error. Moreover, for your function, the error is never raised.
Bug 2. Redundancy. If x is not prime, you call isPrime for each value (let's call it i) from 2 to x/2. isPrime cycles for each number from 2 to sqrt(i). Therefore, isPrime(i) takes O(sqrt(i)) time, and we call it for i from 2 to x/2. Roughly, its running time is about O(x^(3/2)). Even if don't know a more optimal approach, this approach asks for memoization.
i have another way:
def Largest_Prime_Factor(n):
prime_factor = 1
i = 2
while i <= n / i:
if n % i == 0:
prime_factor = i
n /= i
else:
i += 1
if prime_factor < n:
prime_factor = n
return prime_factor
it faster than previous
try it:
import math
def maxPrimeFactors (n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
n = 600851475143
print(maxPrimeFactors(n))
Question:
Given the prime number n, output the number of prime numbers
My code:
def kthPrime(self, n):
if n>10 and n%10 not in [1,3,7,9]:
return 0
if n == 2:
return 1
queue = []
num = 2
while num <= n:
if n%num == 0 and num != n:
return 0
if num>10 and num%10 not in [1,3,7,9]:
num += 1
continue
for i in range(2,num/2+1):
if num%i == 0:
num += 1
break
else:
queue.append(num)
num += 1
seq = queue.index(n) + 1
return seq
Error:
Your code ran too much time than we expected. Check your time complexity. Time limit exceeded usually caused by infinite loop if your time complexity is the best.
My Question: how to improve it
as user #Prune said , please read the guide first.
I'm not going to tell you how to improve your function , but I'm just gonna give you a faster way to see whether a number is prime or not and hopefully you will understand how to use the function that I'm gonna give you to improve your own function.
The source code :
class numChecker:
def is_prime(self,n):
if n == 2:
return True
if n % 2 == 0 or n < 2:
return False
self.square_root = int(n ** (1/2))
for divisor in range(3, self.square_root + 1, +2):
if n % divisor == 0:
return False
return True
I recently started messing around with python and I wrote a program to print out the 1000th prime number but the output only shows a blinking cursor , the code is shown below:
number = 3
count= 1
while count <= 1000:
prime = True
for x in range(2, number):
if number % x == 0:
prime= False
if prime == True:
count = count + 1
if count <= 1000:
number = number + 1
print number
Any help and concise explanation would be appreciated
edit: i just realized the problem. #tichodroma solved the problem but did so by editing the OP post. so when i got to it it was already solved, how ever, he solved it by putting the print into the loop, hence the many numbers waterfall. but it should be outside the loop so as to only show the final result. also - after looking at the OP code before edit, it was written in such a way that it was taking a long time to run, and the "blinking line" was the system working in the background
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
counter = 0
number = 0
while True:
if isprime(number):
counter+=1
if counter == 10000:
break
number+=1
print number