简体   繁体   中英

How to transform this code to work for more than two numbers (calculating HCF)

I don't know how to make this code to work for more than two numbers. It works perfectly for two numbers.

#include <iostream>
using namespace std;

int main() {

    int n1, n2;

    cout << "   Insert 2 numbers: ";
    cin >> n1 >> n2;

    while(n1 != n2)
    {
        if(n1 > n2)
        {
            n1 -= n2;
        }

        else
        {
            n2 -= n1;
        }
    }

i   cout << "HCF = " << n1; return 0;
}

For example if we input 6 and 12 the code says 6 which is right.

Just turn your calculation into a function:

#include <iostream>

int hcf(int n1, int n2);

int main() {

    int n1, n2, n3;

    std::cout << "   Insert 3 numbers: ";
    std::cin >> n1 >> n2 >> n3;

    std::cout << "HCF = " << hcf(n1, hcf(n2, n3));

    return 0;
}

int hcf(int n1, int n2) {

    while (n1 != n2) {

        if (n1 > n2)
            n1 -= n2;

        else
            n2 -= n1;

    }

    return n1;
}

Now you can easily calculate HCF for as many numbers as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM