Recommended Posts
- Get link
- X
- Other Apps
prime_finder.py
import tkinter as tk
from tkinter import messagebox
import numpy as np
def find_primes():
try:
upper_limit = int(upper_limit_entry.get())
if upper_limit < 2:
raise ValueError("Upper limit must be at least 2.")
# Create a boolean array representing numbers from 0 to upper_limit
is_prime = np.ones(upper_limit + 1, dtype=bool)
is_prime[0] = is_prime[1] = False # 0 and 1 are not prime
# Sieve of Eratosthenes algorithm
for i in range(2, int(np.sqrt(upper_limit)) + 1):
if is_prime[i]:
is_prime[i*i::i] = False # Mark multiples of i as not prime
primes = np.arange(2, upper_limit + 1)[is_prime[2:]]
result_label.config(text="Prime Numbers: " + str(primes))
except ValueError as e:
messagebox.showerror("Error", str(e))
root = tk.Tk()
root.title("Prime Number Finder")
upper_limit_label = tk.Label(root, text="Upper Limit:")
upper_limit_label.pack()
upper_limit_entry = tk.Entry(root)
upper_limit_entry.pack()
find_button = tk.Button(root, text="Find Primes", command=find_primes)
find_button.pack(pady=10)
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()
-How to Run the Code:
- Install Python: Ensure you have Python installed on your system (version 3.6 or higher is recommended).
- Install Libraries: Open a terminal or command prompt and install the necessary libraries using pip:
pip install tkinter numpy
-
- Save the Code: Save the code as a Python file (e.g., prime_finder.py).
- Run the Script: Execute the script from your terminal:
python prime_finder.py
-
A window will appear with an input field for the upper limit. Enter the desired value and click the "Find Primes" button to find and display the prime numbers within that range.
Code Explanation:
- Import Libraries: The code imports tkinter for the GUI, messagebox for displaying error messages, and numpy for array manipulation and efficient calculations.
- find_primes() Function: This function is called when the "Find Primes" button is clicked. It retrieves the upper limit from the entry field. It validates the input to ensure that the upper limit is at least 2. If the input is valid, it uses the Sieve of Eratosthenes algorithm to find the prime numbers.
- Sieve of Eratosthenes: This algorithm efficiently finds all prime numbers up to a given limit. It creates a boolean array is_prime where is_prime[i] is True if i is prime and False otherwise. Initially, all numbers are assumed to be prime. The algorithm then iterates through the numbers starting from 2. For each prime number i, it marks all multiples of i as not prime.
- NumPy Implementation: The code uses NumPy's array slicing and boolean indexing to efficiently implement the Sieve of Eratosthenes. is_prime[i*i::i] = False marks all multiples of i starting from i*i as not prime.
- Extracting Primes: After the Sieve of Eratosthenes algorithm is complete, the code extracts the prime numbers from the is_prime array using boolean indexing: primes = np.arange(2, upper_limit + 1)[is_prime[2:]].
- Displaying Results: The prime numbers are then displayed in the result_label. If the input is invalid, a ValueError is raised, and an error message is displayed using messagebox.showerror().
- GUI Creation: The code creates the main window (root), a label and entry field for the upper limit, a button to trigger the prime number search, and a label to display the results.
- Button Command: The command attribute of the "Find Primes" button is set to the find_primes() function.
- root.mainloop(): This starts the Tkinter event loop, which listens for user interactions and updates the GUI accordingly.
Comments
Post a Comment