Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java problem 20 #131

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions javaProblems/problem20/Solution.java
Original file line number Diff line number Diff line change
@@ -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(", ");
}
}
}
}
}
36 changes: 36 additions & 0 deletions javaProblems/problem20/Test.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
}

11 changes: 11 additions & 0 deletions javaProblems/problem20/readme.md
Original file line number Diff line number Diff line change
@@ -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


Loading