Digital Roots?


  • 0
    A

    So I was trying to figure out what is unique about square numbers and found this article:

    http://burningmath.blogspot.ca/2013/09/how-to-check-if-number-is-perfect-square.html

    Which involves finding the digital root of the number you are trying to check and if that root is either 1,4,7,9 then your number is a perfect square. This method however does not seem to work for certain test cases such as 2147483647. I was wondering if I my understanding of digital roots and this method is wrong or this method just doesn't work for some cases (in which case it is useless).

    Here is my code:

    bool isPerfectSquare(int num) {
    if(num==1){
    	return true;
    }   
    
    int root = 0;
    int result = rootIs(num);
    while(result>9){
    	std::cout << result << std::endl;
    	result = rootIs(result);
    }   
    
    //Result is digital root of num, if digital root is 1,4,7,9 then number is a square most likely
    if(result == 1 || result==4 || result==7 || result==9){
    	return true;
    }
    return false;   
    
    }   
    
    //Returns sum of digits of num
    int rootIs(int num){
    int result = 0;
    while(num){
    	result+=num%10;
    	num = num/10;
    }
    return result;
    }
    

    Sorry in advance if the formatting is wrong or something, I am new to Leetcode and this forum. Thank you for any advice or help!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.