Day 15 - Java

Problem Statement: Prime Numbers in Range

You are given a Java program that reads two integers representing a range (inclusive) from standard input. The program then finds and prints all prime numbers within that range. The findPrimes function generates a list of prime numbers within the given range, and the isPrime function determines whether a number is prime or not.

Your task is to write test cases to validate the correctness of the findPrimes and isPrime functions. Ensure that the functions work as expected and handle edge cases appropriately.

Instructions:

findPrimes(int start, int end):

This function takes two integers start and end representing the range.

It returns a list of prime numbers within the specified range.

Use streams and functional programming techniques to generate the list of prime numbers efficiently.

isPrime(int n):

This function takes an integer n as input.

It returns true if the input number is prime, otherwise false.

Use the provided logic to determine whether a number is prime or not.

Sample Input 1:

10 50

Sample Output 1:

11 13 17 19 23 29 31 37 41 43 47

Explanation 1:

The input range is from 10 to 50 (inclusive).

Prime numbers within this range are: 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.

Sample Input 2:

1 20

Sample Output 2:

2 3 5 7 11 13 17 19

Explanation 2:

The input range is from 1 to 20 (inclusive).

Prime numbers within this range are: 2, 3, 5, 7, 11, 13, 17, 19.

These prime numbers are printed in a single line separated by a space.


SOLUTION:

import java.util.List;

import java.util.Scanner;

import java.util.stream.Collectors;

import java.util.stream.IntStream;

public class Program {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        String[] arr = sc.nextLine().split(" ");

        int s = Integer.parseInt(arr[0]);

        int e = Integer.parseInt(arr[1]);

        List<Integer> primeNumbers = findPrimes(s, e);

        System.out.println(primeNumbers.stream()

                            .map(Object::toString)

                            .collect(Collectors.joining(" ")));

        sc.close();

    }

   

    public static List<Integer> findPrimes(int start, int end) {

        return IntStream.rangeClosed(start, end)

            .filter(Program::isPrime)

            .boxed()

            .collect(Collectors.toList());

    }

    

    public static boolean isPrime(int n) {

        if (n <= 1) {

            return false;

        }

        return IntStream.rangeClosed(2, (int) Math.sqrt(n))

            .allMatch(i -> n % i != 0);

    }

}


Insights:

  • The findPrimes() method generates a list of prime numbers within the specified range. It uses IntStream.rangeClosed() to generate a stream of integers within the range, then filters out non-prime numbers using the isPrime() method.
  • The isPrime() method checks whether a given number is prime or not. It iterates from 2 to the square root of the number and checks if the number is divisible by any of these values. If it finds any divisor, it returns false, indicating that the number is not prime. Otherwise, it returns true.
  • The prime numbers found by findPrimes() method are boxed to Integer objects and collected into a List<Integer> using the collect() method.
  • The program prints the list of prime numbers obtained in the previous step by converting them to strings and joining them with a space using collect(Collectors.joining()).
  • The program uses Java 8 streams and functional programming techniques to efficiently generate and process the prime numbers within the given range. The program follows a simple class structure with a Program class containing the main method along with helper methods for finding primes and checking primality. The methods are static and can be called without instantiating the class.

Simpler Method:

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class Program {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        String[] arr = sc.nextLine().split(" ");

        int s = Integer.parseInt(arr[0]);

        int e = Integer.parseInt(arr[1]);

        List<Integer> primeNumbers = findPrimes(s, e);

        for (int prime : primeNumbers) {

            System.out.print(prime + " ");

        }

        sc.close();

    }

    

    public static List<Integer> findPrimes(int start, int end) {

        List<Integer> primes = new ArrayList<>();

        for (int i = start; i <= end; i++) {

            if (isPrime(i)) {

                primes.add(i);

            }

        }

        return primes;

    }

    

    public static boolean isPrime(int n) {

        if (n <= 1) {

            return false;

        }

        for (int i = 2; i <= Math.sqrt(n); i++) {

            if (n % i == 0) {

                return false;

            }

        }

        return true;

    }

}

Embrace the challenge of prime numbers and shine ðŸŒŸ uniquely in your mathematical and Coding exploration! #CoderTheExplorer 

Happy Coding! :)


Comments