C# program to check given numbers are the pair of amicable numbers or not

Here, we are going to learn how to check given numbers are the pair of amicable numbers or not in C#? By Nidhi Last updated : April 15, 2023

What are Amicable numbers?

Amicable numbers are pair of two numbers; here some of the proper divisors of both numbers are equal. The same two numbers are not considered as amicable.

Determining Two Numbers are Amicable

Here we will enter two integer numbers from the keyboard and then checked the entered numbers are amicable or not.

C# code for determining two numbers are amicable or not

The source code to check given numbers are the pair of amicable numbers or not is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to check given numbers are 
//the pair of amicable numbers or not.

using System;

class Demo
{

    static bool IsAmicable(int number1, int number2)
    {
        int sum1 = 0;
        int sum2 = 0;
        int X    = 0;

        for (X = 1; X < number1; X++)
        {
            if (number1 % X == 0)
            {
                sum1 = sum1 + X;
            }
        }
        for (X = 1; X < number2; X++)
        {
            if (number2 % X == 0)
            {
                sum2 = sum2 + X;
            }
        }

        if (number1 == sum2 && number2 == sum1)
            return true;

        return false;
    }
    static void Main(string[] args)
    {
        int number1=0;
        int number2=0;
    
        Console.Write("Enter 1st Number : ");
        number1 = Convert.ToInt32(Console.ReadLine());
        
        Console.Write("Enter 2nd Number : ");
        number2 = Convert.ToInt32(Console.ReadLine());

        if (IsAmicable(number1, number2))
            Console.WriteLine("Numbers are the pair of Amicable numbers");
        else
            Console.WriteLine("Numbers are not the pair of Amicable numbers");
    }
}

Output

Enter 1st Number : 220
Enter 2nd Number : 284
Numbers are the pair of Amicable numbers
Press any key to continue . . .

Explanation

Here, we created a class Demo that contains two methods IsAmicable() and Main(). In the IsAmicable(), we checked amicable numbers from two numbers.

Amicable numbers are pair of two numbers; here some of the proper divisors of both numbers are equal. The same two numbers are not considered as amicable.

In the Main() method, we read the values of two integer numbers and then checked pair of amicable numbers. Then printed the corresponding message according to the return value of the IsAmicable() method on the console screen.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.