C# Kaprekar Transformation 3 Digit Number ends with 495
I have given here C# code for Kaprekar Transformation for a 3 digit number. The logic is as follows:
1. Make sure the given number is 3 digits.
2. Make sure all the digits are not same.
3. With the given number, form two numbers with descending and ascending 3 digits.
4. Subtract the small number from the big number.
5. Take the difference as a new number and repeat step 3 until you reach 495.
Source Code
using System;
using System.Collections.Generic;
using System.Text;
namespace KaprekarTranformation
{
class KaprekarTranformation
{
static int ComputeKaprekarTranformation(int number)
{
int a1, a2, a3;
int d1, d2, d3;
int big, small, diff;
int digit1 = number / 100; // MSB
int digit2 = (number - digit1 * 100) / 10;
int digit3 = (number % 10); // LSB
if (digit1 > digit2)
{
if (digit1 > digit3)
{
d1 = digit1;
if (digit2 > digit3)
{
d2 = digit2;
d3 = digit3;
}
else
{
d3 = digit2;
d2 = digit3;
}
}
else
{
d1 = digit3;
d2 = digit1;
d3 = digit2;
}
}
else
{
if (digit2 > digit3)
{
d1 = digit2;
if (digit1 > digit3)
{
d2 = digit1;
d3 = digit3;
}
else
{
d3 = digit1;
d2 = digit3;
}
}
else
{
d1 = digit3;
d2 = digit2;
d3 = digit1;
}
}
if (digit1 < digit2)
{
if (digit1 < digit3)
{
a1 = digit1;
if (digit2 < digit3)
{
a2 = digit2;
a3 = digit3;
}
else
{
a3 = digit2;
a2 = digit3;
}
}
else
{
a1 = digit3;
a2 = digit1;
a3 = digit2;
}
}
else
{
if (digit2 < digit3)
{
a1 = digit2;
if (digit1 < digit3)
{
a2 = digit1;
a3 = digit3;
}
else
{
a3 = digit1;
a2 = digit3;
}
}
else
{
a1 = digit3;
a2 = digit2;
a3 = digit1;
}
}
big = d1 * 100 + d2 * 10 + d3;
small = a1 * 100 + a2 * 10 + a3;
diff = big - small;
System.Console.Write("{0} - {1} = {2}\n", big, small, diff);
return diff;
}
static void Main(string[] args)
{
System.Console.Write("Enter a 3 digit number for Kaprekar Tranformation: ");
string input = System.Console.ReadLine();
int number = Convert.ToInt32(input);
if (number < 0 || number > 999)
{
System.Console.WriteLine("Your input is not correct.");
}
int digit1 = number / 100; // MSB
int digit2 = (number - digit1 * 100) / 10;
int digit3 = (number % 10); // LSB
if (digit1 == digit2 && digit1 == digit3)
{
System.Console.WriteLine("All digits should not be equal.");
return;
}
while (true)
{
int nextnumber = ComputeKaprekarTranformation(number);
if (number == nextnumber)
break;
number = nextnumber;
}
}
}
}
Output
|