c# - Happy number out put -


i doing happy number exercise. fyi https://en.wikipedia.org/wiki/happy_number here code

using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks;  namespace consoleapplication23 {     class program     {         static void main(string[] args)         {             list<string> happynum = new list<string>();             program test = new program();             string number = "7";             if (test.checkhappy(number))             {                 happynum.add(number);             }              if (happynum.contains(number))             {                 console.writeline("1");             }             else             {                 console.writeline("0");             }          }         public bool checkhappy(string num) {             int sum = 0;             int temp = int.parse(num);             while (temp != 1) {                 while (temp != 0)                 {                     int digit = temp % 10;                     sum += digit * digit;                     temp = temp / 10;                 }                 temp = sum;                 sum = 0;             }             return true;         }     } } 

when put "true" happy number 7, 1, console print 1, when put 22, 435, doesn't print 0 please !!!

according wiki, if number unhappy algorithm loop endlessly in cycle not include 1. never prints 0 got got stuck in infinite loop. however, when algorithm ends in cycle of repeating numbers, cycle includes number 4, have add if statement terminate while loop when number unhappy.

while (temp != 0) {     int digit = temp % 10;     sum += digit * digit;     temp = temp / 10;      //you need stop infinite loop      if (sum == 4)           return false; } 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -