Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Describe a non recursive algorithm that takes a list of distinct integers and st

ID: 3581341 • Letter: D

Question

Describe a non recursive algorithm that takes a list of distinct integers and stock the sum of the reciprocals of the primes. Write you answer in pseudo code or any wolf known potential language like Python, Java, C++, .... You may assume that a function "x is prime" has been defined, where "x is prime" applied to a prime number returns TRUE and "x is prime" applied to a returns FALSE Recall that the reciprocal of a is y_a Sum Of Reciprocals Of Primes (a_1, a_2, ...a_n integers) b) Describe a recursive algorithm that takes a list L of distinct integers and finds the finds the sum of the reciprocals of the primes. Write your answer in pseudo-code or any well known procedural language like Python, Java, C++, .... In addition to the "prime x" function above, you may assume that you have three functions that work on lists i) "L is empty" which returns TRUE if a given list is empty, FALSE otherwise ii) "first of L" which returns the first element of a given nonempty list. iii) "rest of L" which returns a list containing all but the first element of a given nonempty list. Note that if the list has only one element, "rest" will return the empty list.

Explanation / Answer

using python 2.7

import math
def is_prime(n):
    for i in range(2, sqrt(n)):
        if n%i==0:
            return False
    return True

def sum_of_reciprocals_of_primes(l):
    sum = 0
    for elem in l:
        if is_prime(elem):
            sum += 1.0/elem
    return sum

b)

import math
def is_prime(n):
    for i in range(2, sqrt(n)):
        if n%i==0:
            return False
    return True

def sum_of_reciprocals_of_primes(l):
    if is_prime(l[0]):
        return 1.0/elem+sum_of_reciprocals_of_primes(l[1:])
    else:
        return sum_of_reciprocals_of_primes(l[1:])

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote