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

a) Describe a non-recursive algorithm that takes a list of distinct integers a_1

ID: 3109369 • Letter: A

Question

a) Describe a non-recursive algorithm that takes a list of distinct integers a_1, a_2, ..., a_n, and 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++, .... You may assume that a function "x is prime" has been defined, where "x is prime" applied to a prime number returns TRUE "x is prime" applied to a nonrpime returns FALSE. Recall that the reciprocal of a is 1/a procedure_sum_Of_Reciprocals_of_Primes(a_1, a_2, ..., a_n:integers)

Explanation / Answer

#include<iostream>
#include<math.h>
using namespace std;

static double sum;

bool isPrime(int x)
{
int k = (int)sqrt(x); // since after square root numbers repeat
int i;
for(i=2;i<=k;i++)
{
if(x%i==0) //Number divisible so not prime
break;

}
if(x==k+1)
return true; //prime
else
return false; //non prime
  
}

void sum_of_reciprocals(double k)
{
sum = sum + k;

}

main()
{
int N,i,x;
//No of integers
cin>>N;
int a[N];
for(i=0;i<N;i++)
{
cin>>x;
bool b = isPrime(x);
if(b==true)
{sum_of_reciprocals(1/x);
  
}

}   
cout<<sum;
  
}