Thursday, September 20, 2018

Java tricks for competitive programming (for Java 8)

Java tricks for competitive programming (for Java 8)

Although practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging.
1) Checking if the number is even or odd without using the % operator:
Although this trick is not much better than using % operator but is sometimes efficient (with large numbers). Use & operator:
System.out.println((a & 1) == 0 "EVEN" : "ODD" );
Example:
num = 5
Binary: “101 & 1” will be 001, so true
num = 4
Binary: “100 & 1” will be 000, so false.
2) Fast Multiplication or Division by 2
Multiplying by 2 means shifting all the bits to left and dividing by 2 means shifting to the right.
Example : 2 (Binary 10): shifting left 4 (Binary 100) and right 1 (Binary 1)
n = n << 1;   // Multiply n with 2
n = n >> 1;   // Divide n by 2
3) Swapping of 2 numbers using XOR: 
This method is fast and doesn’t require the use of 3rd variable.
// A quick way to swap a and b
a ^= b;
b ^= a;
a ^= b; 
4) Faster I/O: 
Refer here for Fast I/O in java

5) For String manipulations: 
Use StringBuffer for string manipulations, as String in java is immutable.Refer here.
6) Calculating the most significant digit: To calculate the most significant digit of any number log can be directly used to calculate it.
Suppose the number is N then 
Let double K = Math.log10(N);
now K = K - Math.floor(K);
int X = (int)Math.pow(10, K);
X will be the most significant digit.
7) Calculating the number of digits directly: To calculate number of digits in a number, instead of looping we can efficiently use log :
No. of digits in N = Math.floor(Math.log10(N)) + 1;
8) Inbuilt GCD Method: Java has inbuilt GCD method in BigInteger class. It returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val). Returns 0 if this==0 && val==0.
Syntax : 
public BigInteger gcd(BigInteger val)
Parameters :
val - value with which the GCD is to be computed.
Returns :
GCD(abs(this), abs(val))
// Java program to demonstrate how
// to use gcd method of BigInteger class
  
import java.math.BigInteger;
      
class Test
{
    public static int gcd(int a, int b) 
    {
        BigInteger b1 = BigInteger.valueOf(a);
        BigInteger b2 = BigInteger.valueOf(b);
        BigInteger gcd = b1.gcd(b2);
            return gcd.intValue();
    }
      
    public static long gcd(long a, long b) 
    {
        BigInteger b1 = BigInteger.valueOf(a);
        BigInteger b2 = BigInteger.valueOf(b);
        BigInteger gcd = b1.gcd(b2);
            return gcd.longValue();
    }
      
           
    // Driver method
    public static void main(String[] args) 
    {
        System.out.println(gcd(3, 5));
        System.out.println(gcd(10000000000L, 600000000L));
    }
}

Output:
1
200000000
9) checking for a prime number: Java has inbuilt isProbablePrime() method in BigInteger class. It returns true if this BigInteger is probably prime(with some certainty), false if it’s definitely composite.
BigInteger.valueOf(1235).isProbablePrime(1)
10) Efficient trick to know if a number is a power of 2 The normal technique of division the complexity comes out to be O(logN), but it can be solved using O(v) where v are the number of digits of number in binary form.
/* Method to check if x is power of 2*/
static boolean isPowerOfTwo (int x)
{
     /* First x in the below expression is 
     for the case when x is 0 */
      return x!=0 && ((x&(x-1)) == 0);    
}
11) Sorting Algorithm:
Arrays.sort() used to sort elements of a array.
Collections.sort() used to sort elements of a collection.
For primitives, Arrays.sort() uses dual pivot quicksort algorithms.
12) Searching Algorithm:
Arrays.binarySearch()(SET 1 | SET2) used to apply binary search on an sorted array.
Collections.binarySearch() used to apply binary search on a collection based on comparators.
13) Copy Algorithm: 
Arrays.copyOf() and copyOfRange() copy the specified array.
Collections.copy() copies specified collection.
14) Rotation and Frequency We can use Collections.rotate() to rotate a collection or an array by a specified distance. You can also use Collections.frequency() method to get frequency of specified element in a collection or an array.
15) Most data structures are already implemented in the Collections Framework. For example : Stack, LinkedList, HashSet, HashMaps, Heaps etc.
16) Use Wrapper class functions for getting radix conversions of a number Sometime you require radix conversion of a number. For this you can use wrapper classes.
// Java program to demonstrate use of wrapper 
// classes for radix conversion
  
class Test
{
    // Driver method
    public static void main(String[] args) 
    {
        int a = 525;
        long b = 12456545645L;
          
        String binaryA = Integer.toString(a, 2);
        System.out.println("Binary representation"
                               " of A : " + binaryA);
        String binaryB = Long.toString(b, 2);
        System.out.println("Binary representation"
                               " of B : " + binaryB);        
        String octalA = Integer.toString(a, 8);
        System.out.println("Octal representation"
                                " of A : " + octalA);
        String octalB = Long.toString(b, 8);
        System.out.println("Octal representation"
                                " of B : " + octalB);        
    }
}

Output:
Binary representation of A : 1000001101
Binary representation of B : 1011100110011101111100110101101101
Octal representation of A : 1015
Octal representation of B : 134635746555
17) NullPointerException(Why ?) Refer here and here to avoid it.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


No comments:

Post a Comment

SQL Important Queries

  How to delete rows with no where clause The following example deletes  all rows  from the  Person.Person  the table in the AdventureWork...