0

my code was for (f=1;f<=num1&&f<=num2;f++) { if (num1%f==0&&num2%f==0) cout<<"the gcd is"<<f; how can i printed the last val. f

how can i print the last value of f. example the number is 12 and 8 ..i want to display the gcd is 4. but in my program it was displaying like this the gcd is 1 the gcd is 2 the gcd is 4 how can i printed the highest value of f.

22nd Oct 2016, 12:28 AM
KG Feignh
KG Feignh - avatar
6 odpowiedzi
+ 2
A quick and simple way would be to create a variable before the loop, assign the value in the loop and print it after the loop.
22nd Oct 2016, 12:46 AM
Liam
Liam - avatar
+ 1
I'm on my phone so can't really type code. Before the loop: int highestFactor=0 In the loop, after the if condition: highestFactor=f After the loop: cout << "highest common factor is " << f
22nd Oct 2016, 12:54 AM
Liam
Liam - avatar
+ 1
int gcf(int a, int b) { if (b == 0) return a; return gcf(b, a&b); } this is a more elegant, recursive function for finding the Greatest Common Factor, if it's useful to this application. you could then make a Least Common Denominator function that calls gcf: int lcd(int denomA, int denomB) { int GCF = gcf(denomA, denomB); return (denomA * denomB) / GCF; }
22nd Oct 2016, 3:09 AM
Zeke Williams
Zeke Williams - avatar
0
example code please
22nd Oct 2016, 12:49 AM
KG Feignh
KG Feignh - avatar
0
thanks
22nd Oct 2016, 1:37 AM
Resha Aditiya
0
nothing changed on the code
22nd Oct 2016, 1:50 AM
KG Feignh
KG Feignh - avatar