# My code is giving me correct output but in submission it shows wrong. Why?

Here is my code…

``````#include <bits/stdc++.h>
using namespace std;
int isDivisible(int a, int b)
{
if (a > b)
{
if (a % b == 0)
{
return 1;
}
else
{
return 0;
}
}
else
{
if (b % a == 0)
{
return 1;
}
else
{
return 0;
}
}
}

void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout<<endl;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int arr[n];
bool flag = false;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int temp[n] = {0};
for (int i = 0; i < n; i++)
{
temp[i] = {arr[i]};
}
sort(arr, arr + n);

for (int i = 1; i < n; i++)
{
if(isDivisible(arr[0],arr[i])==1){
flag = true;
}
else{
flag = false;
break;
}
}
if (flag == true)
{
int ans[n] = {0};
for (int i = 0; i < n; i++)
{
ans[i] = {temp[i]/arr[0]};
}
printArray(ans, n);
}
else
{
printArray(temp, n);
}
}
return 0;
}

``````

Hi, @arnab2002

Thanks for posting the problem link. In summary, RECIPE wants you to reduce the ingredients to the smallest integer values that maintain the same proportions.

Your algorithm works if the smallest ingredient evenly divides all the others, such as…
`3 15 9 6`

All elements are divisible by 3, so you correctly output `1 5 3 2`.

But your algorithm fails if the elements have some other common divisor, such as…
`4 6`

The right answer is `2 3`, but your algorithm doesn’t output that.

I hope this helps you track down the problem!

2 Likes

Hi, @sbatten1969 I am still having problem. Can you please examine my code? Where is my fault?

``````#include <bits/stdc++.h>
using namespace std;
bool allElementSame(int arr[],int n){
bool flag = true;
for(int i=1; i<n; i++){
if(arr[0]==arr[i]){
flag = true;
}
else{
flag = false;
}
}
return flag;
}
int factor(int a, int b){
int ans;
if(a<b){
for(int i=2;i<=b; i++){
if(a%i==0&&b%i==0)
ans = i;
}
}
else if(b<a)
{
for(int i=2;i<=a; i++){
if(b%i==0&&a%i==0)
ans = i;
}
}
else if (a == b)
{
ans = 1;
}
return ans;
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout<<endl;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int temp[n] = {0};
for (int i = 0; i < n; i++)
{
temp[i] = {arr[i]};
}
sort(arr, arr + n);
int test = factor(arr[0],arr[1]);
bool flag = false;
for(int i = 1; i < n; i++) {
if(factor(arr[0],arr[i])==test){
flag = true;
}
else
{
flag = false;
break;
}
}
if (flag == true && allElementSame(arr,n) == false)
{
int ans[n] = {0};
for (int i = 0; i < n; i++)
{
ans[i] = {temp[i]/test};
}
printArray(ans, n);
}
if (flag == true && allElementSame(arr,n) == true)
{
int ans[n] = {0};
for (int i = 0; i < n; i++)
{
ans[i] = {temp[i]/arr[0]};
}
printArray(ans, n);
}
else if(flag == false && allElementSame(arr,n) == false)
{
printArray(temp, n);
}
}
return 0;
}

``````
1 Like

Ok. Done… Thank you so much sir.
I have done the code correctly & now it shows me correct answer.

1 Like