Think like the best software engineer and give e the code for : Write a prime number program in java
Question:
Think like the best software engineer and give e the code for : Write a prime number program in java
This is AI generated Response.
Asked by: Test User 100158
Created at: 2025-05-12 01:16:13
Asked by: Test User 100158
Created at: 2025-05-12 01:16:13
Final Answer:
Rendered
Raw Text
Did you like this answer?
Absolutely! Here’s a clean, efficient Java program to **check if a number is a prime**, along with **printing all prime numbers up to a given limit**. This will help you with both use cases.
---
### 1. **Check if a Number is Prime**
```java
import java.util.Scanner;
public class PrimeChecker {
// Efficient prime check (O(sqrt(n)))
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
int sqrt = (int)Math.sqrt(n);
for (int i = 3; i <= sqrt; i += 2) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (isPrime(num)) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is NOT a prime number.");
}
sc.close();
}
}
```
---
### 2. **Print All Primes up to N**
```java
import java.util.Scanner;
public class PrimesUpToN {
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
int sqrt = (int)Math.sqrt(n);
for (int i = 3; i <= sqrt; i += 2) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Find primes up to: ");
int limit = sc.nextInt();
System.out.print("Prime numbers up to " + limit + ": ");
for (int i = 2; i <= limit; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
sc.close();
}
}
```
---
**Key Points:**
- Efficient prime check: only up to √n, skip even numbers after 2.
- Handles edge cases (n ≤ 1).
- Clean, readable code.
Let me know if you need an even faster algorithm (like Sieve of Eratosthenes for all primes up to N)!
📢 Instructions:
- Ask anything relatd to above question only.
- For new Question goto :
VIPSolutions