Programming Projects

Welcome to the Land of Programming Projects

This site hosts projects related to C, C++, .NET, PHP, MYSQL, Javascript and other programming languages.


Project Title: Greatest Common Divisor (GCD) Of Two Numbers

Description: This project finds the Greatest Common Divisor (GCD) of two input numbers using a simple iterative function.

Difficulty: Easy

Language: Visual Basic.NET (VB.NET)

Compiler: Visual Studio

View Source

            
            
Module Module1

    Sub Main()

        Dim n1, n2 As Integer
        Console.WriteLine("Enter first number")
        n1 = Console.ReadLine
        Console.WriteLine("Enter second number")
        n2 = Console.ReadLine

        Console.WriteLine("GCD of " & n1 & " and " & n2 & " is " & gcd(n1, n2))
        Console.ReadLine()

    End Sub

    Function gcd(ByVal n1 As Integer, ByVal n2 As Integer) As Integer

        Dim minimum As Integer
        If n1 < n2 Then
            minimum = n1
        Else
            minimum = n2
        End If

        For i As Integer = minimum To 1 Step -1
            If n1 Mod i = 0 And n2 Mod i = 0 Then
                Return i
            End If
        Next


    End Function

End Module

   


Notes: The project calls the GCD function. This function first determines the minimum of the two numbers. Then we check if the minimum divides both the numbers. If it does, this is our GCD, otherwise we continue on checking numbers less than the minimum.

Note that this project uses an iterative method for computing GCD, there is another project Decimal To Rational that uses a recursive approach. Check that out!