2 simple Java solutions - via Stream and a contant time


  • 1

    Via Stream

    boolean checkPerfectNumber(int num) {
      return (num >= 6) && (num == (divisors(num).sum() + 1));
    }
    IntStream divisors(int num) {
      return IntStream.rangeClosed(2, (int) Math.sqrt(num))
                      .filter(i -> num % i == 0)
                      .flatMap(i -> IntStream.of(i, num / i));
    }
    

    or in a single line, if you're into that:

    boolean checkPerfectNumber(int num) {
      return (num >= 6) && (num == IntStream.rangeClosed(2, (int) Math.sqrt(num)).filter(i -> num % i == 0).flatMap(i -> IntStream.of(i, num / i)).sum() + 1);
    }
    

    or a constant time alternative, since there are only a few perfect numbers that are small enough:

    boolean checkPerfectNumber(int num) {
      switch(num) {
        case 6: case 28: case 496: case 8_128: case 33_550_336: return true;
        default: return false;
      }
    }
    

  • 0

    @paplorinc
    It seems you quite value the length of the code block.

        public boolean checkPerfectNumber(int num) {
            List<Integer> list = new LinkedList(Arrays.asList(6, 28, 496, 8_128, 33_550_336));
            return list.contains(num); 
        }

  • 0

    @zzhai sure, I could have written

    return Arrays.asList(6, 28, 496, 8_128, 33_550_336).contains(num); 
    

    also, but a switch can decide whether linear search is faster than binary search for the given arguments, while searching over an array (especially a linked list) is always linear and slow.


Log in to reply
 

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