Product array puzzle
PROBLEM :
Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i].
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input A[i].
Output:
Print the Product array prod[].
Constraints:
1 = T = 10
1 = N = 15
1 = C[i] = 20
Example:
Input
2
5
10 3 5 6 2
2
12 20
Output
180 600 360 300 900
20 12
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t ;
cin>>t ;
while(t--)
{
int no ;
cin>>no ;
int arr[no] ;
for(int i=0;i<no;i++)
cin>>arr[i] ;
int prod[no] ;
for(int i=0;i<no;i++)
prod[i]=1 ;
int temp ;
temp=1 ;
for(int i=0;i<no;i++)
{
prod[i]*=temp ;
temp*=arr[i] ;
}
temp=1 ;
for(int i=no-1;i>=0;i--)
{
prod[i]*=temp ;
temp*=arr[i] ;
}
for(int i=0;i<no;i++)
cout<<prod[i]<<" " ;
cout<<endl ;
}
return 0;
}
---------------------------------------------------------------------------------
Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i].
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input A[i].
Output:
Print the Product array prod[].
Constraints:
1 = T = 10
1 = N = 15
1 = C[i] = 20
Example:
Input
2
5
10 3 5 6 2
2
12 20
Output
180 600 360 300 900
20 12
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t ;
cin>>t ;
while(t--)
{
int no ;
cin>>no ;
int arr[no] ;
for(int i=0;i<no;i++)
cin>>arr[i] ;
int prod[no] ;
for(int i=0;i<no;i++)
prod[i]=1 ;
int temp ;
temp=1 ;
for(int i=0;i<no;i++)
{
prod[i]*=temp ;
temp*=arr[i] ;
}
temp=1 ;
for(int i=no-1;i>=0;i--)
{
prod[i]*=temp ;
temp*=arr[i] ;
}
for(int i=0;i<no;i++)
cout<<prod[i]<<" " ;
cout<<endl ;
}
return 0;
}
---------------------------------------------------------------------------------
Comments
Post a Comment