+ 5

Counting Ratio

How can I count more than two ratio in programming? Mainly I code with c++. It can easily do it between two numbers. But when the ratio between more than two, I can't. Help to make an algorithm. One more thing to consider that, the output of ratio will be in integer formate!

12th Dec 2018, 9:39 AM
Coder
Coder - avatar
8 Antworten
+ 4
Even if you had n numbers, you can just call your gcd function using a loop, like I said towards the end of my last comment. Something like g=a[0]; for (i=1; i<n; ++i) { g = gcd(g, a[i]); }
12th Dec 2018, 12:19 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 6
Just divide them all by their GCD (greatest common divisor). Say we have 18, 30, and 96. Then their GCD is 6, and when we divide them by 6 we get 3, 5, and 16. So their ratio is 18:30:96 = 3:5:16. This is also how I'd do it for two numbers, by the way. Hope that helps 😊
12th Dec 2018, 10:51 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 5
Kishalaya Saha The main problem is that I can't calculate GCD for more than two. So the main challenge is to calculate the GCD of more than two numbers. Hope you can realize my problem!
12th Dec 2018, 11:57 AM
Coder
Coder - avatar
+ 5
Thanks. I have fixed the bug.
12th Dec 2018, 12:40 PM
Coder
Coder - avatar
+ 4
After a lot of try, I myself solved the problem: [Edited] #include<iostream> using namespace std; int main(){ int c,n,i,j,min; cin>>n; int ar [n]; for(i=0;i<n;i++) cin>>ar[i]; min=ar[0]; for(i=1;i<n;i++){ if(ar[i]<min) min=ar[i]; } for(j=2;j<=min;){ for(i=0,c=0;i<n;i++){ if(ar[i]%j!=0){ c++; break; } } if(!c){ for(i=0;i<n;i++) ar[i]/=j; min/=j; j=2; } else j++; } for(i=0;i<n;i++) cout<<ar[i]<<" "; cout<<endl; return 0; } https://code.sololearn.com/c6me6Lx2lPfD/?ref=app
12th Dec 2018, 12:06 PM
Coder
Coder - avatar
+ 4
Kishalaya Saha Thanks to you. I didn't know that I can also use that function in that way. But... If there is n numbers! I have also make a program.
12th Dec 2018, 12:13 PM
Coder
Coder - avatar
+ 3
You can do it iteratively/recursively. To compute the GCD of a, b, and c, first get the GCD of a and b, and then find the GCD of that number and c: gcd(a, b, c) = gcd(gcd(a, b), c) It's a lot like how you find the sum of the elements in an array. Just instead of doing sum = sum + a[i], call your gcd function: result = gcd(result, a[i]); Does that make sense?
12th Dec 2018, 12:05 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
And your code looks good to me! It's pretty nice and straightforward. Only one small remark: in lines 20-24, if you divide the array elements by j, their minimum would change as well. So you no longer need to go as far as the old min value. You might like to update it inside the loop as well. Just a min /= j; before resetting j=2 should do the job. Personally I use the Euclidean algorithm to find GCD instead of checking the numbers one by one.
12th Dec 2018, 12:29 PM
Kishalaya Saha
Kishalaya Saha - avatar