Happy Python exercises of digital

Happy Digital

description

  Write an algorithm to determine whether a number is "happy." Happy figure is determined as follows: starting from a positive integer, with each square of which number and the number of substituents, and repeat the process until the final digital convergence or equal to 1 and equal to 1 has been, or will cycle endlessly and ultimately will not go convergence equal to 1. 1 can equal the number of final convergence is a happy number.

  For example: figure 19 is a happy, calculated as follows:

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

  When happy when digital input, output True, otherwise output False. 

Examples

  Input: 19 Output: True

Analysis of casual working

  First, we need to get a number, determine whether it is few, and then were taken each of its digits, then adding the square, so the cycle continues until the final result is 1, the output True, otherwise output False.

  So, if a number is not a happy number, it will not be an infinite loop forever? We can find a few figures to give it a try.

  2:2**2=4;4**2=16;1**2+6**2=37;3**2+7**2=58;5**2+8**2=89;8**2+9**2=145;1**2+4**2+5**2=42;4**2+2**2=20;2**2+0**2=4......

  21:2**2+1**2=5;5**2=25;2**2+5**2=29;2**2+9**2=85;8**2+5**2=89;8**2+9**2=145;1**2+4**2+5**2=42;4**2+2**2=20;2**2+0**2=4......

  35:3**2+5**2=34;3**2+4**2=25;5**2=25;2**2+5**2=29;2**2+9**2=85;8**2+5**2=89;8**2+9**2=145;1**2+4**2+5**2=42;4**2+2**2=20;2**2+0**2=4......

  57:5**2+7**2=74;7**2+4**2=65;6**2+5**2=61;6**2+1**2=37;3**2+7**2=58;5**2+8**2=89;8**2+9**2=145;1**2+4**2+5**2=42;4**2+2**2=20;2**2+0**2=4......

  123:1**2+2**2+3**2=14;1**2+4**2=17;1**2+7**2=50;5**2+0**2=25;2**2+5**2=29;2**2+9**2=85;8**2+5**2=89;8**2+9**2=145;1**2+4**2+5**2=42;4**2+2**2=20;2**2+0**2=4......

  91:9**2+1**2=82;8**2+2**2=68;6**2+8**2=100;1**2+0**2+0**2=1

  Thus, we can see that if a happy number, then the last calculated value of 1; not the number of happy, there must be the result of the final calculation of 4. Can be defined as the cycle determination condition 1 and 4, i.e. when out of the loop and is 1 or 4, in order to prevent infinite loops.

The results show the code and run

  Function method

   operation result

 

   Exception handling

   operation result

 

  This is currently two methods I think, if there are other ways you are welcome to discuss with me!

 

 

 

 


 

Guess you like

Origin www.cnblogs.com/Chen-K/p/11598021.html