Modify the sum_thread.cpp program to compute harmonic sum = 1 + 1/2 + 1/3 + 1/4 + … 1/n.
Let’s estimate natural using n = 20.
sum_thread.cpp
#include <chrono> #include <iostream> #include <mutex> #include <random> #include <utility> #include <vector> #include <thread> using namespace std; constexpr long long size= 1000000; mutex myMutex; void sumUp(unsigned long long& sum, const vector<int>& val, unsigned long long beg, unsigned long long end){ long long localSum = 0; for (auto it= beg; it < end; ++it){ localSum+= val[it]; } lock_guard<mutex> myLock(myMutex); sum += localSum; } int main(){ cout << endl; vector<int> randValues; randValues.reserve(size); mt19937 engine (0); uniform_int_distribution<> uniformDist(1,10); for ( long long i=0 ; i< size ; ++i) randValues.push_back(uniformDist(engine)); unsigned long long sum= 0; auto start = chrono::system_clock::now(); int threads = 4; thread t[threads]; long long slice = size / threads; int startIdx=0; for (int i = 0; i < threads; ++i) { cout << "Thread[" << i << "] - slice [" << startIdx << ":" << startIdx+slice-1 << "]" << endl; t[i] = thread(sumUp, ref(sum), ref(randValues), startIdx, startIdx+slice-1); startIdx += slice; } for (int i = 0; i < threads; ++i) t[i].join(); chrono::duration<double> dur= chrono::system_clock::now() - start; cout << "Time for addition " << dur.count() << " seconds" << endl; cout << "Result: " << sum << endl; cout << endl; }
// C++ program to find sum of harmonic series
#include<bits/stdc++.h>
using
namespace
std;
// Function to return sum of harmonic series
double
sum(
int
n)
{
double
i, s =
0.0;
for
(i = 1; i <=
n; i++)
s = s + 1
/ i;
return
s;
}
// Driver code
int
main()
{
int
n =
5;
cout <<
"Sum is "
<< sum(n);
return
0;
}
You can also use this code:
#include<iostream>
using namespace std;
int main()
{
long d,n,a;
long an;
cout<<"Enter first term : ";
cin>>a;
cout<<"Enter difference : ";
cin>>d;
cout<<"Enter number of terms :";
cin>>n;
cout<<"Harmonic progression : ";
for(int y=1;y<=n;y++)
{
an=a+(y-1)*d;
cout<<"1/"<<an<<" ";
}
return 0;
}
Also Use this code:
Harmonic progression is a series whose inverse will be an
arithmetic progression. i.e. if for a harmonic progression A1, A2,
A3.. An, there is an arithmetic
progression 1/A1, 1/A2, 1/A3.
So, a general HP is :
1/a, 1/(a+d), 1/(a+2d), … 1/(a + nd),where 1/a is the first term
and d is the common difference of the reversed AP.
Input:a = 3, d = 2, n = 5
Output:The sum of HP is 0.878211
Execution:Sum = ⅓ + ⅕ + 1/7 + 1/9 + 1/11 = 0.878211
Code:
#include <iostream>
using namespace std;
float findSeriesSum(int a, int d, int n){
float sumVal = 0;
float term = 0;
for(float i = 1; i <= n; i++){
term = (1.0)/(float)(a + (i-1)*d);
sumVal += term;
}
return sumVal;
}
int main(){
int n, a, d ;
cin>>n>>a>>d;
cout<<"The sum of HP is "<<findSeriesSum(a, d,
n);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.