Java 17 ms using virtual root !=1 property to filter out ~90% of numbers


  • 0
    M

    I added a check to discard on constant time if the digital root of n != 1 property (except 6). More info here https://en.wikipedia.org/wiki/Digital_root

    public class Solution {
        public boolean checkPerfectNumber(int num) {
            if (num == 6) return true;
            if (digRoot(num) != 1) return false;
            int sum =1;
            for (int i =2; i<= Math.sqrt(num); i++) {
                if (num % i ==0) sum += i + (num /i);
            }
            return num!=1 && sum == num;
         
        }
        public int digRoot(int num){
            if (num == 0 ) return 0;
            if (num % 9 == 0) return 9;
            return 1 + ((num-1) %9);
        }
    }
    

Log in to reply
 

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