Question: Overview and Requirements For this micro assignment you are going to write a basic Python program. Python Program - Part 1 (35 pts) Write a
Overview and Requirements
For this micro assignment you are going to write a basic Python program.
Python Program - Part 1 (35 pts)
Write a program (primality_test.py) that prompts the user for an integer, n, where n>=2, determines if the input value is a prime number, and prints out the result. The program should handle invalid inputs and corner cases (eg. n<2) well and should not throw errors.
Within the program, define a predicate function, is_prime(n), that accepts an integer argument n and returns True if n is prime, False otherwise.
Note: To determine if a number is prime or not, implement the trial division approach described below.
-
A natural number (i.e. 1, 2, 3, 4, 5, 6, etc.) is called a prime number (or a prime) if it has exactly two positive divisors, 1 and the number itself. Natural numbers greater than 1 that are not prime are called composite.
-
Trial division approach details (adapted from Wikipedia):
Given an input number n, check whether any prime integer m from 2 to nn evenly divides n (the division leaves no remainder). If n is divisible by any m then n is composite, otherwise it is prime.
For example, we can do a trial division to test the primality of 100. Let's look at all the divisors of 100:
2, 4, 5, 10, 20, 25, 50
If we take a closer look at the divisors, we will see that some of them are redundant. If we write the list differently:
100 = 2 50 = 4 25 = 5 20 = 10 10 = 20 5 = 25 4 = 50 2
the redundancy becomes obvious. Once we reach 10, which is 100100, the divisors just flip around and repeat. Therefore, we can further eliminate testing divisors greater than nn.
Example program outputs (Part 1 only):
Please enter an integer >= 2: 100 100 is not prime! Please enter an integer >= 2: 17 17 is prime!
Python Program - Part 2 (15 pts)
Extend your previous program to compute sum of prime numbers. For this part of the solution, implement a function called sum_primes(M) that accepts an integer M as an argument and returns the sum of all primes from 2 to M.
Key functions of the program:
- Prompt the user for another integer, M.
- Make sure the program handles invalid inputs and corner cases (eg. M<2) well and does not throw errors.
- Determines sum of all prime numbers from 2 to M (i.e. sum of x, such that 2<=x<=M).
- Print the resulting sum to the console.
Example program outputs (Parts 1 & 2):
Please enter an integer >= 2: 100 100 is not prime! Sum of primes from 2 to 100 is 1060! Please enter an integer >= 2: 17 17 is prime! Sum of primes from 2 to 17 is 58!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
