Java Program to Find Prime Numbers in a Range

A number is called a prime number if it has only two divisors, 1 and the number itself. So the only way to express the number as a product of two numbers is,  n = n * 1.  For example, 7 is a prime number while 8 is not since 8 = 2 * 4.

There are various algorithms to find whether a number is a prime number or not. One of the easiest and slowest methods is  the trial division method. In this method we divide the number to be checked with numbers ranging from 2 to square root of the number and see whether any of them is a divisor (a number which can divide without leaving a remainder) of the number. The reason why we need to check only up to square root is because if  n = a * b, both a and b cannot be greater than square root of n!

Finding Prime Numbers in a Range of Natural Numbers

The following Java program finds all the prime numbers in a given range of natural numbers. This program uses the trial division technique for checking whether a number is prime or not. The program also prints out the total number of prime numbers found in the range.

/* Java program to find prime numbers in a range of natural numbers */

public class PrimeNumberRange {

    public static void main(String[] args) {
        long starting_number = 2L;
        long ending_number = 100L;
        long totals = 0;

        System.out.println("List of prime numbers between " + starting_number + " and " + ending_number);

        for (long current = starting_number; current <= ending_number; current++) {
            long sqr_root = (long) Math.sqrt(current);
            boolean is_prime = true;
            for (long i = 2; i <= sqr_root; i++) {
                if (current % i == 0) {
                    is_prime = false; // Current is not prime.
                }
            }
            if (is_prime) {
                System.out.println(current);
                totals++;
            }
        }
        System.out.println("There are a total of "+totals+" prime numbers between "+starting_number+" and "+ending_number);
    }
}

Note that for ranges containing large numbers, this algorithm is very slow due to the sheer number of mathematical operations required.

Prime Number Checker in Java Using Trial Division

A prime number is a natural number which can only be divided(without leaving a remainder) by 1 and the number itself. For example, number 5 is a prime number since it can be divided by 1 and 5. Number 6 is not a prime since it can be divided by 2 and 3 without leaving a reminder!

One of the easiest ways to check whether a number is a prime or not is to use trial division. In this method we will divide the number by consecutive natural numbers starting with 2 and ending at (number - 1). If we are able to divide it by a number without leaving a remainder, we know that the number is not prime.

However for a number n, we don't need to do trial division till (n-1). We only need to check for prime up to square root of n. This is because if n = a * b, both a and b cannot be greater than square root of n!

Check Prime Number in Java

The following Java program uses trial division up to square root of n to check whether n is a prime. This program may take forever to execute for very large numbers!,

public class PrimeNumberChecker {

    public static void main(String[] args) {
        long number = 98764321261L; 
       
        long sqr_root = (long)Math.sqrt(number);
        for (long i = 2; i <= sqr_root; i++) {
            if (number % i == 0) {
                System.out.println(number+" is NOT prime. It is found to be a product of "+i+" and "+number/i);
                return; // don't process anything
            }
        }
        System.out.println(number+" is a prime number!");
    }
}

Note that for very large numbers, this is method is very slow since it has do a large number of mathematical operations. For the prime number 9876432123444371, the above program took about one second and for the prime number 987643212344434391 it took over 10 seconds!

Floyd’s triangle in Java

Floyd's triangle is a is a right angled triangle of natural numbers. Printing Floyd's triangle is usually given as a programming exercise while learning a new language. It is formed by multiple rows of continuously increasing natural numbers with each row having increasing number of natural numbers. One interesting feature of Floyd's triangle is that in each row the last number is a triangular number corresponding to the row number! An n-th triangular number is equal to the sum of all numbers starting from 1 up to n.

For example, the following is a Floyd's triangle with 5 rows,

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

In the above diagram, 4th row has 10 as the last number which is the triangular number for that row (1+2+3+4 = 10)!

Floyd's triangle in Java

The following Java program creates a Floyd's triangle with the specified number of rows.

/* Program to print Floyd's Triangle in Java */
public class FloydTriangle {
    
    public static void main(String[] args) {
        int rows = 6 ;
        printFloydTriangle(rows);
    }
    
    public static void printFloydTriangle(int rows) {
        int current = 1;
        for(int i=1;i<=rows ;i++) {
            for(int j=1;j<=i;j++) {
                System.out.format("%-3d",current++);  // left justified in 3 spaces
            }
            System.out.println();
        }
    }
    
}

 

Note the use of the format string "%-3d". This tells the formatter to print the number left justified within 3 character spaces. This creates a neatly formatted Floyd's Triangle.

Creating Multiplication Table in Java

A multiplication table is a table of numbers which lists product of a decimal sequence of numbers. For example, a multiplication table of 9 by 9 contains a top most row with values ranging from 1 to 9 and a left most row with values ranging from 1 to 9. The middle cells contains the algebraic product of the corresponding value in the top row and left most row. Following is a 5 by 5 multiplication table,

  1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25

Using a multiplication table it is easy to find product of two numbers. For example, to find the product of 4 and 5, we just need to look at the cell located on the 4th row and 5th column which returns the result as 20.

It is important to memorize multiplication tables as it the foundation of mathematical calculations. Children are usually taught to memorize multiplication tables up to 9 by 9. This enables children to do multiply large numbers without the need of a calculator.

The technique of memorizing the table was to take one column at a time and then memorize it. For example, the multiplication table for number 7 is memorized as,

1 x 7 7
2 x 7 14
3 x 7 21
4 x 7 28
5 x 7 35
6 x 7 42
7 x 7 49
8 x 7 56
9 x 7 63
10 x 7 70

 

Java Program to Print a 9 by 9 Multiplication Table

The following Java program generates the entire multiplication table for values from 1 to 9. This is printed in a formatted table. We use nested loops to generate the multiplication table. Also note the use of System.out.format() method to format the table. The format string %4d instructs the formatter to print the integer in 4 character width padding with spaces as necessary.

/* Prints multiplication table in Java */
public class FullMultiplicationTable {
    
    public static void main(String[] args) {
        int tableSize = 9;
        printMultiplicationTable(tableSize);
    }
    
    public static void printMultiplicationTable(int tableSize) {
        // first print the top header row
        System.out.format("      ");
        for(int i = 1; i<=tableSize;i++ ) {
            System.out.format("%4d",i);
        }
        System.out.println();
        System.out.println("------------------------------------------");
        
        for(int i = 1 ;i<=tableSize;i++) {
            // print left most column first
            System.out.format("%4d |",i);
            for(int j=1;j<=tableSize;j++) {
                System.out.format("%4d",i*j);
            }
            System.out.println();
        }
    }
    
}

The output generated by the multiplication table program in java is given below,

A 9 by 9 multiplication table in Java

Java Program to Print Multiplication Table for an Integer

The following program generates multiplication table for an integer. The table contains product values for the integer when it is multiplied with values ranging from 1 to 10. This form is usually used to memorize the multiplication table,

/* Generates multiplication table for an integer */
public class MultiplicationTable {

    public static void main(String[] args) {
        int number = 7;
        
        printMultiplicationTable(number);
    }

    private static void printMultiplicationTable(int n) {
       System.out.println("Multiplication table for "+n);
       System.out.println("---------------------------");
       for(int i = 1; i<=10;i++) {
           System.out.format("%2d x %d = %3d\n", i,n,i*n);
       }
    }
    
}

The formatted multiplication table output is given below,

Multiplication table for 7

Celsius to Fahrenheit Conversion in Java

The formula for converting temperature in Celsius to Fahrenheit is,

Fahrenheit = (9/5) * Celsius + 32

For example, if the temperature is 35 in Celsius, the equivalent value in Fahrenheit is (9/5) * 35 + 32 = 95 F.

The formula for converting temperature in Fahrenheit to Celsius is,

Celsius = (5/9) * (Fahrenheit - 32)

For example, if the temperature is 95 in Fahrenheit, the equivalent value in Celsius is (5/9)* (95-32) = 35.

The following table is a conversion table between Celsius and Fahrenheit values (some values are approximate)

Celsius (C) Fahrenheit (F)
100 212
40 104
37 98.6
30 86
21 70
10 50
0 32
-18 0
-40 -40

 

Java Program to Convert Celsius to Fahrenheit

The following Java program converts the user entered temperature value in Celsius to Fahrenheit,

// Celsius to Fahrenheit conversion in Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CelsiusToFahrenheit {
    
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter temperature in Celsius : ");
        double celsius = Double.parseDouble(reader.readLine());
        double fahrenheit = (9.0/5.0)*celsius + 32;
        System.out.println("Temperature in Fahrenheit is : "+fahrenheit);
    }
}

Note the use of double values 9.0 and 5.0. If we use 9 and 5, the results would be wrong since 9/5 would evaluate to an integer.

Java Program to Convert Fahrenheit to Celsius

The following Java program converts the user entered temperature value in Fahrenheit to Celsius ,

// Fahrenheit to Celsius conversion in Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FahrenheitToCelsius {
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter temperature in Fahrenheit : ");
        double fahrenheit = Double.parseDouble(reader.readLine());
        double celsius = (5.0/9.0)*(fahrenheit - 32);
        System.out.println("Temperature in Celsius is : "+celsius);
    }
}