Skip to main content

Posts

Showing posts from August, 2018

Random Numbers in Java

In this post we will go through the basics of generating random numbers and also see how they can be generated within a range along with best practices. Java provides support to either generate random numbers through java.lang.Math package or java.util.Random . Using java.lang.Math There exists a static method inside this class, Math.random . It is very convenient to use and returns a double between the range 0.0 and 1.0 i.e. it returns a floating point number between 0 and 1. public static void main(String[] args){ double randNum = Math.random(); System.out.println(randNum); } Random number within a range - To generate a random number within a range we need to further process the number returned by Math.random() public static void main (String[] args){ double min = 10.0; double max = 100.0; double randNum = randRange(min, max); System.out.println(randNum); } public static double randRange(double min, double max){ double x = (Math.rando

Fast Multiplication of Long Integeres | Karatsuba's Algorithm

This article is divided into 3 parts, so feel free to skip around to the part you find useful - Need for the algorithm Intuition and Algorithm Implementation Need for the algorithm Multiplication is an elementary concept known to all of us since a very early age. But multiplication of very large numbers becomes a difficult problem that can't be solved mentally unless you're a mathematical genius and hence we use calculators and computers. Computers too can efficiently multiply numbers but as the length of digits of the number increases, the time complexity also increases along with it quadratically. To calculate the product of humongous numbers we need a better algorithm. Any algorithm that even slightly increases the runtime will prove to be very beneficial for large values of n, say 100000. Karatsuba multiplication algorithm brings down the number of operations by a factor of one and gives a huge boost. Intuition and Algorithm Okay so, to boost up the speed of