DSA Codes
DSA Codes
Sieve Algorithm :
• Time Complexity : The dominant term in the .me complexity is O(n log log n), which makes
this the overall .me complexity of the algorithm. The Sieve of Eratosthenes is very efficient
for genera.ng all primes up to a large number.
• Space Complexity : The space complexity of the Sieve of Eratosthenes algorithm is O(n),
where n is the upper limit up to which we want to find prime numbers.
Program
prime[i] = true;
if (prime[p] == true) {
prime[i] = false;
if (prime[p] == true) {
simpleSieve(50);
} }
2. Segmented Sieve Algorithm
Space Complexity : The space complexity is O(h - l + 1) for the boolean array prime that
stores whether each number in the range
Program :
import java.u.l.*;
public class Main {
sta.c void SegSieve(int l, int h) {
boolean prime[] = new boolean[h - l + 1];
Arrays.fill(prime, true);
if (l == 1)
l = 2;
for (int p = 2; p * p <= h; p++) {
Program :
import java.u.l.*;
// Check for all prime factors of n and subtract their mul.ples from result
if (n % p == 0) { // p is a prime factor of n
n /= p;
result -= result / p;
// If n has a prime factor greater than sqrt(n), then add its contribu.on
if (n > 1) {
result -= result / n;
return result;
int n = sc.nextInt();
sc.close(); }}
4. StrobogrammaJc number :
Program :
import java.u.l.*;
class Main {
map.put('6', '9');
map.put('9', '6');
map.put('0', '0');
map.put('1', '1');
map.put('8', '8');
int l = 0, r = num.length() - 1;
while (l <= r) {
if (map.get(num.charAt(l)) != num.charAt(r))
return false;
l++;
r--;
return true;
String n= "8698";
System.out.println(result); } }
5. Chinese remainder Theorem
Time Complexity: O(k * P), where k is the number of modular conditions and P is the
product of all the elements in the num[] array.
Space Complexity : O(k)
Program :
import java.u.l.*;
class Main {
int j , x = 1;
while(true)
for( j=0;j<k;j++)
if(x%num[j] != rem[j] )
break;
if(j ==k)
return x;
x++;} }
System.out.println("Enter Divisor");
int k= sc.nextInt();
num[i] = sc.nextInt();
System.out.println("Enter Remainder");
int rem[]=new int[k];
rem[i] = sc.nextInt();
} }
Program :
import java.u.l.Scanner;
class Main{
int n=sc.nextInt();
int i,j,c=0;
for(i=1;i<=n;i++)
for(j=i;j<=n;j+=i)
if(b[j]==false)
b[j] = true;
else
b[j] = false;
}}
for(i=1;i<=n;i++)
{
if(b[i]==true)
c++;
System.out.println(c);
Program :
import java.u.l.*;
int n=sc.nextInt();
int cnt=0,sum=0;
while(sum<n){
cnt++;
sum+=(12*cnt*cnt);
System.out.println((8*(cnt)));