ViijayScript: 06/14/16

Tuesday, 14 June 2016

#Program to #find #HCF and #LCM in #C #C++ #Java C# #Python

Hello netizens, On this post I am going to tell #Programs to #find #LCM and #HCF of a #number in #C #C++ #Java C# #Python.

Program in C:

#include <stdio.h>
long gcd(long, long);
int main() {
long x, y, hcf, lcm;
printf(“Enter two integers\n”);
scanf(“%ld%ld”, &x, &y);
hcf = gcd(x, y);
lcm = (x*y)/hcf;
printf(“Greatest common divisor of %ld and %ld = %ld\n”, x, y, hcf);
printf(“Least common multiple of %ld and %ld = %ld\n”, x, y, lcm);
return 0;
}
/ if 1st no is 0 then 2nd no is gcd
make 2nd no 0 by subtracting smallest from largest and return 1st no as gcd /
long gcd(long x, long y) {
if (x == 0) {
return y;
}
while (y != 0) {
if (x > y) {
x = x – y;
}
else {
y = y – x;
}
}
return x;
}

Program in C++:

#include <iostream>
#include <string>
using namespace std;
int main()
{
int a,b,c;
cout<< "Enter two nos :" <<endl;
cout<<endl;
cout<>a;
cout<>b;
c=a*b;
while(a!=b)
{
if (a>b)
a=a-b;
else
b=b-a;
}
cout<< "HCF = " << a<<endl;
cout<< "LCM = " << c/a<<endl;
return 0;
}

Program in Java:

import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int a, b, x, y, t, hcf, lcm;
Scanner scan = new Scanner(System.in);
System.out.print(“Enter Two Number : “);
x = scan.nextInt();
y = scan.nextInt();
a = x;
b = y;
while(b != 0)
{
t = b;
b = a%b;
a = t;
}
hcf = a;
lcm = (x*y)/hcf;
System.out.print(“HCF = ” +hcf);
System.out.print(“\nLCM = ” +lcm);
}
}

Program in C#:

1. using System ;
2. using System .Text ;
3.
4. namespace forgetCode
5. {
6.
7. class program
8. {
9. public static void Main ()
10. {
11. int a , b , x , y , t , gcd , lcm ;
12. Console. WriteLine (“Enter two integers\n” );
13. x = Convert .ToInt32 ( Console.ReadLine
());
14. y =
Convert .ToInt32 ( Console.ReadLine ());
15.
16. a = x ;
17. b = y ;
18.
19. while (b != 0 )
20. {
21. t = b ;
22. b = a % b ;
23. a = t ;
24. }
25.
26. gcd = a ;
27. lcm = ( x * y ) / gcd ;
28. Console. WriteLine (“Greatest common divisor of {0} and {1}= {2}\n” , x , y , gcd);
29. Console. WriteLine (“Least common multiple of{0} and {1}= {2}\n” , x , y , lcm );
30.
31.
32. }
33. }
34. }

Program in Python:

d1 = int ( raw_input ( “Enter a number:”))
d2 = int ( raw_input ( “Enter another number”))
rem = d1 % d2
while rem!=0:
d1=d2
d2 = rem
rem = d1 % d2
print “gcd of given numbers is : %d” %(d2)
x = int(input(“Enter first number: “))
y= int(input(“Enter second number: “))
if x>y:
g=x
else:
g=y
while(True):
if((g % x ==0) and (g % y==0)):
lcm=g
break
g += 1
print “L.C.M is “,lcm

If our post is helpful then share it with your near and dear ones.

Scan this QR Code on LinkedIn

Scan this QR Code on LinkedIn