Problems - Set 1
Prime Number
Apply Sieve of Eratosthenes Algorithm
import java.util.ArrayList;
public class SieveOfEratosthenes {
public static ArrayList<Integer> findPrimes(int n) {
// Step 1: Initialize a boolean array to keep track of prime numbers
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
isPrime[i] = true; // Assume all numbers from 2 to n are prime initially
}
// Step 2: Apply the sieve algorithm
for (int p = 2; p * p <= n; p++) {
if (isPrime[p]) {
// Mark all multiples of p as non-prime
for (int multiple = p * p; multiple <= n; multiple += p) {
isPrime[multiple] = false;
}
}
}
// Step 3: Collect all prime numbers into an ArrayList
ArrayList<Integer> primes = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.add(i); // Add prime number to the list
}
}
return primes; // Return the sorted ArrayList of primes
}
public static void main(String[] args) {
int n = 50; // Example: Find all primes up to 50
ArrayList<Integer> primes = findPrimes(n);
System.out.println("Prime numbers up to " + n + ": " + primes);
}
}Time Complexity Analysis
Program to Swap Two Numbers
Convert Decimal number to Binary number
Using Arrays

Using Bitwise Operators
Without using arrays
Using inbuit method
Convert Binary number to Decimal number
Binary Arithmetic
Add two binary numbers given in long format
Method 1: Using inbuilt method
Method 2: Using Modulo Division
Multiply two binary numbers given in long format
Method 1: Using inbuilt method
Method 2: Using Modulo operation
Factorial of a number
Small number
Iterative Solution
Using Recursive Method
Using Stream
Large number
Using BigIntegers
Using Basic Maths Operation with the help of array i.e. storing digits in array and considering carry which helps in increasing size of array.
Print Pascal Triangle

Using nCr formula

Using Binomial Coefficient
Method 1:
Method 2:
Print fibonacci series
Using Iterative Method
Using Recursive Method
Print number triangle


Find Transpose of Matrix
Square Matrix
Method 1: Using additional array
Method 2: WIthout using additional array
Rectangular Matrix

GCD or HCF of two numbers

Using Iteration
Using Euclidean algorithm for GCD of two numbers (Involves Recursion)

Optimization Euclidean algorithm by checking divisibility

Optimization using division
Iterative implementation using Euclidean Algorithm
Using in-built function in Java for BigIntegers
LCM of two numbers
Using GCD of 2 numbers and Formula
Using Iterative method
Find All Factors of a Number
Last updated