write a program to calculate the Highest Common Factor of three input numbers

Dani AI

Generated

For computing the HCF of three integers, the fast, robust choice is the Euclidean approach that pointed to; the brute-force loop suggested by is both slower and (as written) has a loop-bound error — if you try a divisor loop, iterate downward from the smaller number, not upward from M to M/2. For real code, prefer standard library helpers where available (they handle signs and zeros cleanly) or fold a tested gcd routine over the inputs.

Example using Python's standard library (no manual algorithm required):

from math import gcd
from functools import reduce

def hcf_of_three(a, b, c):
    vals = [abs(int(x)) for x in (a, b, c)]
    if all(v == 0 for v in vals):
        return 0  # behaviour: many libraries return 0 for (0,0,0)
    return reduce(gcd, vals)

print(hcf_of_three(100, 125, 75))  # 25

Example using modern C++ (C++17 or later):

#include <numeric>
#include <iostream>
#include <cstdlib>

int main() {
    long long a, b, c;
    if (!(std::cin >> a >> b >> c)) return 0;
    a = llabs(a); b = llabs(b); c = llabs(c);
    if (a==0 && b==0 && c==0) { std::cout << 0 << '\n'; return 0; }
    std::cout << std::gcd(a, std::gcd(b, c)) << '\n';
}

Notes and pitfalls:

  • Take absolute values first so negative inputs behave as expected.
  • Decide how to treat (0,0,0) — many libraries return 0, though mathematically gcd(0,0) is undefined.
  • For C (no std::gcd), either implement an iterative gcd carefully or call a library routine; avoid naive divisor searches for large inputs.
  • Euclid-based gcd runs in about O(log min(a,b)), so it scales well for big integers.

Recommended Answers

All 2 Replies

I give algorithm you try it in C#

HCF (GCD) Algorithm

GCD ( M, N ) {
If N > M then return GCD ( N, M )
else If N = 0 then return M
else return GCD ( N, MOD ( M, N) )
}

It is simple to covert it to C#
Also it is for two input

For three input

GCD ( M, N, O ){
return GCD ( M, GCD ( N, O ) )
}

I give algorithm you try it in C#

HCF (GCD) Algorithm

GCD ( M, N ) {
If N > M then return GCD ( N, M )
else If N = 0 then return M
else return GCD ( N, MOD ( M, N) )
}

It is simple to covert it to C#
Also it is for two input

For three input

GCD ( M, N, O ){
return GCD ( M, GCD ( N, O ) )
}

Hie,

Thanks buddy, but i didnt really get the algo.
Heres the one from me:
=======
1 Input: num type variables M,N, HCF. (eg: M=100, N=125)
2 Find the smaller one from M,n. (eg: smaller: M)
3 Start a loop from M to M/2. (eg: i=m;i<=m/2;i++)
___1 Check whether i%m=0 & i%n==0.
___2 HCF = i; break;

Hope this can help you! :)

Regards,
PuneetKay

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.