In: Computer Science
Improve the algorithm by using two for loops instead of three, and analyze the running time of your improved algorithm asymptotically. Show the modified code.
Algorithm FactorSum(A, n)
Input: Array A of n real numbers.
S ← 0
for i ← 0 to n - 1
for j ← i to n - 1
P ← 1
for k ← i to j
P ← P x A[k]
S ← S + P
return S
Algorithm:
int p;
if(i!=0)
p = cumulative_multiplication[j]/cumulative_multiplication[i-1];
else
p = cumulative_multiplication[j];
Old Program ( 3 loops ):
#include<bits/stdc++.h>
using namespace std;
int main()
{
int s = 0;
int n = 8;
int A[n] = {1,2,4,5,45,6,78,9}; // Input array A of size n
// 1st loop
for(int i=0;i<=n-1;i++)
{
// 2nd Loop
for(int j=i;j<=n-1;j++)
{
// 3rd Loop
int p = 1;
for(int k=i;k<=j;k++)
{
p = p * A[k];
}
s = s + p;
}
}
// Finally printing the value of s
cout << "With 3-loops\n" << endl;
cout << "Value of s: " << s << endl;
return 0;
}
Output:
New Program ( 2 loops ):
#include<bits/stdc++.h>
using namespace std;
int main()
{
int s = 0;
int n = 8;
int A[n] = {1,2,4,5,45,6,78,9}; // Input array A of size n
long int cumulative_multiplication[n]; // Declaring an array to store cumulative multiplication
// Finding the cumulative multiplication
cumulative_multiplication[0] = A[0];
for(int i=1;i<=n-1;i++)
{
cumulative_multiplication[i] = A[i] * cumulative_multiplication[i-1];
}
// 1st loop
for(int i=0;i<=n-1;i++)
{
// Second loop
for(int j=i;j<=n-1;j++)
{
// Replacing thirst loop with cumulative multiplication
int p;
if(i!=0)
p = cumulative_multiplication[j]/cumulative_multiplication[i-1];
else
p = cumulative_multiplication[j];
s = s + p;
}
}
// Finally printing the value of s
cout << "With 2-loops\n" << endl;
cout << "Value of s: " << s << endl;
return 0;
}
Output:
Please let me know in the comments in case of any confusion. Also, please UPVOTE if you like.