Ahil1991 commited on
Commit
def393d
·
verified ·
1 Parent(s): 4ae5ea2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -13
app.py CHANGED
@@ -1,28 +1,56 @@
1
  import gradio as gr
 
2
  import time
 
3
 
 
4
  def is_prime(n):
5
  if n < 2:
6
  return False
7
- for i in range(2, int(n**0.5) + 1):
8
- if n % i == 0:
 
 
 
 
9
  return False
10
  return True
11
 
12
- def prime_generator():
13
- num = 2
14
- while True:
15
- if is_prime(num):
16
- yield str(num) # Yield the prime number as a string
17
- num += 1
18
- time.sleep(0.5) # Adjust the sleep time to control the speed of prime generation
19
 
 
20
  def start_prime_printer():
21
- prime_stream = prime_generator()
 
22
  output = []
23
- for prime in prime_stream:
24
- output.append(prime)
25
- yield "\n".join(output) # Update the output in the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  # Gradio Interface
28
  interface = gr.Interface(
 
1
  import gradio as gr
2
+ import multiprocessing
3
  import time
4
+ from math import isqrt
5
 
6
+ # Function to check if a number is prime
7
  def is_prime(n):
8
  if n < 2:
9
  return False
10
+ if n in (2, 3):
11
+ return True
12
+ if n % 2 == 0 or n % 3 == 0:
13
+ return False
14
+ for i in range(5, isqrt(n) + 1, 6):
15
+ if n % i == 0 or n % (i + 2) == 0:
16
  return False
17
  return True
18
 
19
+ # Function to find the next prime number in a given range
20
+ def find_primes_in_range(start, end, queue):
21
+ primes = [str(num) for num in range(start, end) if is_prime(num)]
22
+ queue.put(primes)
 
 
 
23
 
24
+ # Function that utilizes multiple processes to find primes
25
  def start_prime_printer():
26
+ num = 2 # Start from the first prime
27
+ batch_size = 1000 # Size of the range each process will handle
28
  output = []
29
+ num_processes = multiprocessing.cpu_count() # Utilize all available CPU cores
30
+
31
+ while True:
32
+ processes = []
33
+ queue = multiprocessing.Queue()
34
+
35
+ # Create and start processes
36
+ for i in range(num_processes):
37
+ start = num + i * batch_size
38
+ end = start + batch_size
39
+ process = multiprocessing.Process(target=find_primes_in_range, args=(start, end, queue))
40
+ process.start()
41
+ processes.append(process)
42
+
43
+ # Collect results from all processes
44
+ for process in processes:
45
+ process.join() # Wait for process to finish
46
+ primes = queue.get() # Get primes from this process
47
+ output.extend(primes)
48
+
49
+ # Display the collected prime numbers
50
+ yield "\n".join(output)
51
+
52
+ num += num_processes * batch_size
53
+ time.sleep(0.1) # Adjust the sleep time if needed to manage UI responsiveness
54
 
55
  # Gradio Interface
56
  interface = gr.Interface(