The tutorial for today is about a math problem named happy number.
I used my repl.it account to test it.
The algorithm of this program is simple:
To find out if a number is happy, replace the number by the sum of the squares of its digits. Repeat the process until either the number equals 1 or loops endlessly in a cycle that does not include 1. When the process ends with 1 then the number is described as a happy number, otherwise, it is an unhappy number.
Let’s test for number 19:
1 2 3 4 | 1*1 + 9*9 = 82 8*8 + 2*2 = 68 6*6 + 8*8 = 100 1*1 + 0*0 + 0*0 = 1 |
You can test the C# source code at:
The source code of this program is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | using System; // check happy number , example: // 13 is a happy number because 13 is 1*1+3*3 = 10 // 19 is a happy number because 19 is // 1*1 + 9*9 = 82 // 8*8 + 2*2 = 68 // 6*6 + 8*8 = 100 // 1*1 + 0*0 + 0*0 = 1 class MainClass { public static void Main (string[] args) { int number; int tmp; int sum = 0; // show a message Console.WriteLine ("Input to test the number: "); // read the number number = Convert.ToInt32(Console.ReadLine()); // start check happy number while (sum != 1 && sum != 4) { sum = 0; while (number > 0) { tmp = number % 10; sum += (tmp * tmp); number = number/10; } number = sum; } if (sum ==1) { Console.WriteLine("This is a happy number!"); } else { Console.WriteLine("Another Unhappy number!"); } // expect to press a key Console.ReadKey(true); } } |