Search
 
SCRIPT & CODE EXAMPLE
 

CPP

how to get hcf of two number in c++

#include<iostream>
using namespace std;

// This method improves complexity of repeated substraction
// By efficient use of modulo operator in euclidean algorithm
int getHCF(int a, int b)
{
    return b == 0 ? a : getHCF(b, a % b); 
}

int main()
{
    int num1 = -36, num2 = 60;

    // if user enters negative number, we just changing it to positive
    // By definition HCF is highest positive number that divides both numbers
    // -36 & 60 : HCF = 12 (as highest num that divides both)
    // -36 & -60 : HCF = 16 (as highest num that divides both)
    num1 = (num1 > 0) ? num1 : -num1;
    num2 = (num2 > 0) ? num2 : -num2;
    
    cout<<"HCF of "<<num1<<" and "<<num2<<" is "<<getHCF(num1, num2);
    
    return 0;
}
// Time Complexity: log(max(a,b))
Comment

PREVIOUS NEXT
Code Example
Cpp :: c++ base constructor 
Cpp :: struct c++ 
Cpp :: ascii cpp 
Cpp :: c++ program to convert kelvin to fahrenheit 
Cpp :: what is meant by pragma once in c++ 
Cpp :: check if element in dict c++ 
Cpp :: cpp lambda function 
Cpp :: How do I read computer current time in c++ 
Cpp :: inserting element in vector in C++ 
Cpp :: cin exceptions c++ 
Cpp :: SUMOFPROD2 codechef solution 
Cpp :: count number of prime numbers in a given range in c 
Cpp :: factorial of large number 
Cpp :: map in cpp 
Cpp :: C++ Nested if...else 
Cpp :: accumulate vector c++ 
Cpp :: vector of threads thread pool c++ 
Cpp :: c++ variable types 
Cpp :: range based for loop c++ 
Cpp :: how to make a vector in c++ 
Cpp :: adddynamic ue4 c++ 
Cpp :: how to reset linerenderer unity 
Cpp :: C++ Arrays and Loops 
Cpp :: print elements of linked list 
Cpp :: c++ string find last number 
Cpp :: maximum subarray leetcode c++ 
Cpp :: what is the time complexitry of std::sort 
Cpp :: order 2d array in c++ 
Cpp :: Valid Parentheses leetcode in c++ 
Cpp :: c++ vector operations 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =