Some common maths concepts.

Primes

  • all primes are of the form 6k ± 1, with the exception of 2 and 3
     private boolean isPrime(int n) {
      // Corner cases 
      if (n <= 1) return false; 
      if (n <= 3) return true; 
        
      // This is checked so that we can skip  
      // middle five numbers in below loop 
      if (n % 2 == 0 || n % 3 == 0) return false; 
        
      for (int i = 5; i * i <= n; i = i + 6) 
          if (n % i == 0 || n % (i + 2) == 0) 
          return false; 
        
      return true; 
    }
    

Digital Root

The digital root (also repeated digital sum) of a natural number in a given number base is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.

Digital root

Perfect Square

Check if a number is perfect squae or not. This is a math problem: 1 = 1 4 = 1 + 3 9 = 1 + 3 + 5 16 = 1 + 3 + 5 + 7 25 = 1 + 3 + 5 + 7 + 9 36 = 1 + 3 + 5 + 7 + 9 + 11 …. so 1+3+…+(2n-1) = (2n-1 + 1)n/2 = nn

public boolean isPerfectSquare(int num) {
    int i = 1;
    while (num > 0) {
        num -= i;
        i += 2;
    }
    return num == 0;
}