Posts

Showing posts with the label GCD

In Java, Find GCD Of Array Of Integers Given By User

Image
import java.util.Scanner; class CalcGcd { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.print("Enter 5 numbers: "); System.out.println("GCD: " + gcd( stdin.nextInt(), stdin.nextInt(), stdin.nextInt(), stdin.nextInt(), stdin.nextInt() )); } public static int gcd(int... numbers){ int result = numbers[0]; for(int i=1; i<numbers.length; i++){ result = findGCD(numbers[i], result); } return result; } public static int findGCD(int a, int b){ if(b == 0) return a; return findGCD(b, a%b); } } Download

How to find HCF/GCD with C#?

Image
using System; public class Test { private static int HCF(int x, int y) { if (0 == x) return y; if (0 == y) return x; if (x == y) return x; if (x < y) return HCF(x, y-x); return HCF(x-y, y); } private static int GCD(int x, int y) { if (0 == y) return x; return GCD(y, x % y); } public static void Main(string[]args) { int x = 14, y = 18; Console.WriteLine("HCF of {0} & {1} is {2}", x, y, HCF(x, y)); Console.WriteLine("GCD of {0} & {1} is {2}", x, y, GCD(x, y)); } }