GCF error D:

closed account (ivDwAqkS)

Revise the program so that it prints out all the steps involved in the
algorithm. Here is a sample output:
GCF (500, 300) =>
GCF (300, 200) =>
GCF (200, 100) =>
GCF (100, 0) => //this line is not printing out.
100

the problem is that the last line is not printing out I mean the (100, 0) and I don't know why, please help me I don't know what I am doing wrong.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cstdlib>
using namespace std;

int Gcf(int a, int b);
void Print_gcf(int a, int b);

int main ()
{
    int a = 0, b = 0;

    cout << "Enter a: ";
    cin >> a;
    cout << "Enter b: ";
    cin >> b;
    cout << Gcf(a, b) << endl;

    return 0;
}

 int Gcf(int a, int b)
 {
    if (b == 0){
        return a;
    }
    else{
        Print_gcf(a,b);
        return Gcf(b, a%b);
    }
 }

 void Print_gcf(int a, int b)
 {
         cout << "GCF (" << a << ") " << "(" << b << ") => " << a%b <<endl;
 }
Last edited on
the problem is that the last line is not printing out I mean the (100, 0) and I don't know why, please help me I don't know what I am doing wrong.


That's what your code does. If you don't want Print_gcf to only be called when b is not 0, then move it from the else clause within Gcf.

1
2
3
4
5
6
7
8
9
int Gcf(int a, int b)
{
    Print_gcf(a,b);

    if ( b == 0 )
        return a ;

    return Gcf(b, a%b) ;
}


Of course, then you will have to make an adjustment to Print_gcf so that you don't divide by 0.
Last edited on
closed account (ivDwAqkS)
wow , thank you so much I was doing this
1
2
3
4
5
6
7
8
9
 int Gcf(int a, int b)
 {
    Print_gcf(a,b);
    return Gcf(b, a%b);

    if (b == 0){
        return a;
    } 
 }

and it caused me error, isn't it the same?
Topic archived. No new replies allowed.