From d50cdd1b1fc22b3e2541cbe33f711cbc26d80b85 Mon Sep 17 00:00:00 2001 From: Sam-wiz Date: Wed, 11 Oct 2023 04:27:38 +0530 Subject: [PATCH] Added all the files --- javaProblems/problem20/Solution.java | 20 ++++++++++++++++ javaProblems/problem20/Test.java | 36 ++++++++++++++++++++++++++++ javaProblems/problem20/readme.md | 11 +++++++++ 3 files changed, 67 insertions(+) create mode 100644 javaProblems/problem20/Solution.java create mode 100644 javaProblems/problem20/Test.java create mode 100644 javaProblems/problem20/readme.md diff --git a/javaProblems/problem20/Solution.java b/javaProblems/problem20/Solution.java new file mode 100644 index 0000000..3e0d561 --- /dev/null +++ b/javaProblems/problem20/Solution.java @@ -0,0 +1,20 @@ +class Solution +{ + public static void printPrimeNumbers(int N) { + for (int i = 2; i <= N; i++) { + boolean isPrime = true; + for (int j = 2; j <= Math.sqrt(i); j++) { + if (i % j == 0) { + isPrime = false; + break; + } + } + if (isPrime) { + System.out.print(i); + if (i != N) { + System.out.print(", "); + } + } + } + } + } diff --git a/javaProblems/problem20/Test.java b/javaProblems/problem20/Test.java new file mode 100644 index 0000000..a773965 --- /dev/null +++ b/javaProblems/problem20/Test.java @@ -0,0 +1,36 @@ +import java.util*; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Test { + public static void main(String[] args) throws Exception { + Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + Solution solveSolution = new Solution(); + int N = 13; // Change N to the desired test case input + String expectedOutput = "2, 3, 5, 7, 11, 13"; // Change to the expected output + + // Redirect standard output to capture the printed numbers + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outputStream)); + + // Call the function to be tested + solveSolution.printPrimeNumbers(N); + + // Restore standard output + System.setOut(System.out); + + // Get the captured output + String actualOutput = outputStream.toString().trim(); + + // Compare the actual and expected outputs + if (actualOutput.equals(expectedOutput)) { + System.out.println("Testcase passed!"); + } else { + logger.log(Level.SEVERE, "Wrong solution!"); + System.exit(1); + } + } +} + diff --git a/javaProblems/problem20/readme.md b/javaProblems/problem20/readme.md new file mode 100644 index 0000000..a0af635 --- /dev/null +++ b/javaProblems/problem20/readme.md @@ -0,0 +1,11 @@ +Given a number N, the task is to print all prime numbers less than or equal to N. +Examples: + + +Input: 7 +Output: 2, 3, 5, 7 + +Input: 13 +Output: 2, 3, 5, 7, 11, 13 + +