0% found this document useful (0 votes)
8 views25 pages

Java Algorithms: Sieve, CRT, and More

The document contains multiple Java programs that implement various algorithms and data structures. Key topics include the Simple Sieve and Segmented Sieve for prime number generation, Euler's Phi function, strobogrammatic numbers, the Chinese Remainder Theorem, and binary palindrome checks. Additional algorithms cover array rotation, maximum product subarray, majority elements, and leaders in an array.

Uploaded by

vanithakumarim60
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views25 pages

Java Algorithms: Sieve, CRT, and More

The document contains multiple Java programs that implement various algorithms and data structures. Key topics include the Simple Sieve and Segmented Sieve for prime number generation, Euler's Phi function, strobogrammatic numbers, the Chinese Remainder Theorem, and binary palindrome checks. Additional algorithms cover array rotation, maximum product subarray, majority elements, and leaders in an array.

Uploaded by

vanithakumarim60
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Simple Sieve :

1) import [Link].*;
class Simplesieve{

public static void main(String[] args){


Scanner sc = new Scanner([Link]);
int n=[Link]();
boolean arr[]=new boolean[n];
[Link](arr,true);
for(int i=2;i<=[Link](n);i++){
if(arr[i]==true){
for (int j = i*i; j <n; j=j+i) {
if(arr[j]==true){
arr[j]=false;
}
}
}
}
for (int i = 2; i <n; i++) {
if(arr[i]==true) {
[Link](i+" ");
}
}
}
}
Segmented sieve :
2) import [Link].*;

class Segmentedsieve {
static int N = 100;
static boolean arr[] = new boolean[N+1];
static void simpleSieve() {
for(int i=2;i<=N;i++) {
arr[i] = true;
}
for(int i=2;i<[Link](N);i++) {
if(arr[i] == true) {
for(int j=i*i; j<=N; j=j+i) {
arr[j] = false;
} }}}
static ArrayList<Integer> generatePrimes(int n)
{
ArrayList<Integer> al = new ArrayList();
for(int i=2;i<[Link](n);i++)
{
if(arr[i] == true)
{
[Link](i);
}
}
return al;
}
public static void main (String[] args) {
Scanner sc = new Scanner([Link]);
int low = [Link](); //80
int high = [Link](); //90
simpleSieve();
ArrayList<Integer> al = generatePrimes(high);

boolean dummy[] = new boolean[high-low+1];


for(int i=0;i<high-low+1;i++)
{
dummy[i] = true;
}
for(int prime: al) {
int firstMultiple = (low/prime) * prime;
if(firstMultiple < low){
firstMultiple = firstMultiple + prime;
}
int start = [Link](firstMultiple, prime*prime);
for(int j=start; j<=high; j+=prime) {
dummy[j-low] = false;
}
}

for(int i=low;i<=high;i++) {
if(dummy[i-low] == true) {
[Link](i + " ");
}}}}
Euler Phi :
3) import [Link].*;
class Main
{
static int phi(int n)
{
int result = n;
for (int p = 2; p * p <= n; ++p)
{
if (n % p == 0)
{
while (n % p == 0)
n /= p;
result -= result / p;
}
}
if (n > 1)
result -= result / n;
return result;
}
public static void main (String[] args)
{
int n=1000;
[Link](phi(n));
}
}
Strobogrammatic Number :
import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
String num = [Link](); if(isStrobogrammatic(num)) {
[Link](num + " is a strobogrammatic number");
}
else {
[Link](num + " is not a strobogrammatic number");
}
[Link](); }
public static boolean isStrobogrammatic(String num) {
Map<Character, Character> strobogrammaticDictonary = new
HashMap<>();
[Link]('0', '0');
[Link]('1', '1');
[Link]('6', '9');
[Link]('8', '8');
[Link]('9', '6');
int n = [Link]();
for(int i = 0 , j = (n-1) ; i <= j ; i++, j--){
char digit_left = [Link](i);
char digit_right = [Link](j);
char mapping = [Link](digit_left, '-');
if(mapping == '-'){
return false;
}
if(mapping != digit_right){
return false;
}
}
return true;
}
}
Chinese Remainder Theorem :
import [Link].*;
class Main {
static int CRT(int a[], int m[], int n, int p) {
int x = 0;
for (int i = 0; i < n; i++) {
int M = p / m[i];
int y = 0;
for (int j = 0; j < m[i]; j++) {
if ((M * j) % m[i] == 1) {
y = j;
break;
}
}
x = x + a[i] * M * y;
}
return x % p;
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of congruence relations: ");
int size = [Link]();
int a[] = new int[size];
[Link]("Enter the values of a (remainders): ");
for (int i = 0; i < size; i++) {
a[i] = [Link]();
}
int m[] = new int[size];
int p = 1;
[Link]("Enter the values of m (moduli): ");
for (int i = 0; i < size; i++) {
m[i] = [Link]();
p = p * m[i];
}
[Link]("The solution is " + CRT(a, m, size, p));
}
}
Binary Palindrome :
4) import [Link].*;
public class Binarypalindrome
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
String s = [Link](n);
if(isPalindrome(s))
[Link]("true");
else
[Link]("false");
}
public static boolean isPalindrome(String s)
{
int n = [Link]();
for (int i=0,j=n-1;i<j;i++,j--)
{
if([Link](i) != [Link](j))
return false;
}
return true ;
}
}
Alice Apple Tree :
import [Link].*;
class Main {
static int minApples(int M,int K,int N,int S,int W,int E)
{
if(M <= S * K)
return M;
else if(M <= S * K + E + W)
return S * K + (M-S * K);
else
return -1;
}
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("Enter no of apples to be collected-");
int M=[Link]();
[Link]("Enter no of apples in each tree-");
int K = [Link]();
[Link]("Enter no of trees in north-");
int N = [Link]();
[Link]("Enter no of trees in south-");
int S = [Link]();
[Link]("Enter no of trees in west-");
int W = [Link]();
[Link]("Enter no of trees in east-");
int E = [Link]();
int ans = minApples(M,K,N,S,W,E);
[Link](ans);
}}
Karatsuba Algorithm :
5) import [Link];
import [Link];
public class KaratsubaAlgorithm {
public static BigInteger karatsuba(BigInteger x, BigInteger y) {
int n = [Link]([Link](), [Link]());
// Base case: if either x or y is small, use standard multiplication
if (n <= 2000) {
return [Link](y);
}
// Split the numbers into two halves
int half = (n + 32) / 64 * 32; // round up to the nearest multiple of 64
bits
BigInteger mask =
[Link](half).subtract([Link]);
BigInteger xLow = [Link](mask);
BigInteger yLow = [Link](mask);
BigInteger xHigh = [Link](half);
BigInteger yHigh = [Link](half);
BigInteger z0 = karatsuba(xLow, yLow);
BigInteger z1 = karatsuba([Link](xHigh), [Link](yHigh));
BigInteger z2 = karatsuba(xHigh, yHigh);
// Combine the results
BigInteger result = [Link](2 *
half).add([Link](z2).subtract(z0).shiftLeft(half)).add(z0);
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first number: ");
BigInteger x = [Link]();
[Link]("Enter the second number: ");
BigInteger y = [Link]();
BigInteger product = karatsuba(x, y);
[Link]("Product: " + product);
}}
6) import [Link];
import [Link];
public class karatsuba2 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first big number: ");
BigInteger a = new BigInteger([Link]());
[Link]("Enter second big number: ");
BigInteger b = new BigInteger([Link]());
BigInteger result = [Link](b);
[Link]("Result: " + result);
}
}

Longest Sequence of 1 after flipping a bit :


7) import [Link];

public class LongestSequenceof1 {


public static int longestOnes(int[] arr, int k) {
int maxLength = 0;
int left = 0; // left side of the window
int zeroCount = 0; // count of zeros in current window

for (int right = 0; right < [Link]; right++) {


// Expand the window by including arr[right]
if (arr[right] == 0) {
zeroCount++;
}

// Shrink the window if zeroCount exceeds k


while (zeroCount > k) {
if (arr[left] == 0) {
zeroCount--;
}
left++; // shrink from left
}
// Update maximum length found so far
maxLength = [Link](maxLength, right - left + 1);
}

return maxLength;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter array elements (0s and 1s only):");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

[Link]("Enter k (max number of 0s you can flip): ");


int k = [Link]();

int result = longestOnes(arr, k);


[Link]("Longest sequence of 1s after flipping at most %d
zero(s): %d%n", k, result);
}
}

Swap two nibbles:


8) import java .util.*;
public class SwapTwoNibbles
{
public static void main (String [] args )
{
Scanner sc = new Scanner([Link]);
int num = [Link]();
int swap = ((num & 0b00001111)<< 4 | (num & 0b11110000)>>4);
int sw = ((swap & 15)<< 4 | (swap & 240)>>4);
int s = ((sw & 0x0F)<< 4 | (sw & 0xF0 )>>4);
[Link](num + " ");
[Link](swap + " ");
[Link](sw + " ");
[Link](s + " ");

}
}
Don’t use all the masking and swapping methods. only for reference.
Array Rotation:
9) import [Link];
class Swap{
static int[] solve(int arr[], int n, int r){
int res[]=new int[n];
for (int i = 0; i <n; i++) {
res[i]=arr[(i+r)%n]; //(n + i - r) % n
}
return res;
}

public static void main (String[] args)


{
Scanner sc = new Scanner([Link]);
int n= [Link]();
int arr[]=new int[n];
for (int i = 0; i < n; i++) {
arr[i]=[Link]();
}
int r=[Link]();
r = r % n;
arr=solve(arr,n,r);
/*for(int i=0;i<r;i++){
arr=solve(arr,n,r);
}*/
for (int i = 0; i <n; i++) {
[Link](arr[i]+" ");
}

}
}

Max Product Subarray :


10) import [Link].*;
import [Link].*;
public class MaxProductSubarray
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter size of the array");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter elements of the array");
for (int i = 0; i < n; i++){
arr[i] = [Link]();
}
int prefix=1;
int suffix=1;
int ans=1;
for(int i=0; i<n;i++){
if(prefix==0)
prefix=1;
if(suffix==0)
suffix=1;
prefix=prefix*arr[i];
suffix=suffix*arr[n-i-1];
ans=[Link](ans,[Link](prefix,suffix));
}
[Link](ans);
}}
Max Sum of Hour Glass :
import [Link].*;
class Main {
static int row = 5;
static int col = 5;
static int findMaxSum(int [][]mat)
{if (row < 3 || col < 3){
[Link]("Not possible to give");
[Link](0);
}
int max_sum = Integer.MIN_VALUE;
for (int i = 0; i < row - 2; i++){
for (int j = 0; j < col - 2; j++){
int sum = (mat[i][j] + mat[i][j + 1] +
mat[i][j + 2]) + (mat[i + 1][j + 1]) +
(mat[i + 2][j] + mat[i + 2][j + 1] +
mat[i + 2][j + 2]);
max_sum = [Link](max_sum, sum);
}}
return max_sum;
}
static public void main (String[] args)
{
// Get the 2d array input from the user
int res = findMaxSum(mat);
[Link]("Maximum sum of hour glass = "+ res);
}
}

Majority Element :
11) import [Link].*;
public class Majorityelement
{
public static void main(String [] args)
{
Scanner sc = new Scanner ([Link]);
int n = [Link]();
int arr [] = new int [n];
for(int i = 0 ; i<n ; i++)
{
arr[i]=[Link]();
}
int result = findMajority(arr);
if (result!= -1)
{
[Link](result);
}
else
{
[Link](result);
}
}
public static int findMajority(int arr[])
{
Map<Integer,Integer> map = new HashMap<>();
for(int x :arr)
{
[Link](x,[Link](x,0)+1);
}
for ([Link]<Integer,Integer> entry : [Link]() )
{
if([Link]()>[Link]/2)
{
return [Link]();
}
}
return -1;
}
}
Leaders in Array :
12) import [Link].*;
public class LeadersinArray {
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int n = [Link]();
int arr [] = new int [n];
for (int i =0;i<n ;i++)
{
arr[i]=[Link]();
}
Compare(arr,n);
}
public static void Compare(int arr[],int n)
{
List<Integer>L=new ArrayList<>();
int Lead = arr[n-1];// last element of the
[Link](Lead);
for(int i = n-2;i>=0;i--)
{
if(arr[i]>Lead)
{
Lead=arr[i];
[Link](Lead);
}
}
[Link](L);
for(int x : L)
{
[Link](x+" ");
}

}
}
Lexicographical first palindrome :

import [Link].*;

public class LexfirstPalindrome {

static String palindrome(TreeMap<Character, Integer> tm) {


String prefix = "", oddStr = "", suffix = "";

for ([Link]<Character, Integer> e : [Link]()) {


int n = [Link]();

for (int i = 0; i < n / 2; i++)


prefix = prefix + [Link]();

if (n % 2 == 1)
oddStr = oddStr + [Link]();
}
if ([Link]() > 1)
return "Can't make a palindrome";

suffix = new StringBuilder(prefix).reverse().toString();

return prefix + oddStr + suffix;


}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the String: ");
String s = [Link]();

TreeMap<Character, Integer> tm = new TreeMap<>();


char[] ch = [Link]();

for (char ele : ch) {


[Link](ele, [Link](ele, 0) + 1);
}

String res = palindrome(tm);


[Link](res);
}
}
Sorting :
13) import [Link].*;
public class arraysort
{
public static void main(String [] args)
{
Scanner s = new Scanner([Link]);
int n = [Link]();
char [] arr = new char [n];
// for integer array int arr = new int[n];
for(int i=0 ;i<n;i++)
{
arr[i] = [Link]().charAt(0);
// for integer input arr[i]=[Link]();
}
[Link](arr);
for(char x:arr)
[Link](x+" ");
}

}
Weighted substring :
14) import [Link].*;
public class WeightedSubstring {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s = [Link]();
String sub = [Link]();
int weight = 0;
if ([Link](sub)) {
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
weight += (ch - 'A' +1);
}
[Link]("Weighted value of substring \"" + sub + "\" is: " +
weight);
} else {
[Link]("Substring not found in the given string.");
}
}
}

Move Hyphen To The Front :


15) import [Link].*;
public class Movehyphen
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s=[Link]();
String s1="";
String s2="";
for(int i=0;i<[Link]();i++){
if([Link](i)=='-'){
s1=s1+[Link](i);
}
else{
s2=s2+[Link](i);
}
}
[Link](s1+s2);
}
}
16) import [Link];
class MoveHyphenToFront {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String input = [Link]();
char[] str = [Link]();
int n = [Link];
char[] result = new char[n];
int hyphenCount = 0;
for (int i = 0; i < n; i++) {
if (str[i] == '-') {
hyphenCount++;
}
}
for (int i = 0; i < hyphenCount; i++) {
result[i] = '-';
}
int j = hyphenCount;
for (int i = 0; i < n; i++) {
if (str[i] != '-') {
result[j++] = str[i];
}
}
[Link]("After moving hyphens to front: " +
[Link](result));
}
}

Sorted Unique Permutations :


17) import [Link].*;
public class uniquestackpermutation {
static void backtrack(Map<Character, Integer> freq, StringBuilder current,
int length, List<String> result) {
if ([Link]() == length) {
[Link]([Link]());
return;
}
for (char ch : [Link]()) {
int count = [Link](ch);
if (count > 0) {
[Link](ch);
[Link](ch, count - 1);
backtrack(freq, current, length, result);
[Link]([Link]() - 1);
[Link](ch, count);
}
}}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter string: ");
String s = [Link]();
// Build frequency map
Map<Character, Integer> freq = new TreeMap<>();
for (char ch : [Link]())
[Link](ch, [Link](ch, 0) + 1);
List<String> result = new ArrayList<>();
backtrack(freq, new StringBuilder(), [Link](), result);

for (String perm : result) {


[Link](perm);
}
}
}
Maneuvering Problem :
18) import [Link].*;
public class Maneuvering {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int m = [Link]();
[Link]();
String instructions = [Link]();
int x = 0, y = 0; // start at (0,0)
for (int i = 0; i < m ; i++) {
char ch = [Link](i);
int newX = x;
int newY = y;
if (ch == 'R') newY++; // move right
else if (ch == 'L') newY--; // move left
else if (ch == 'U') newX--; // move up
else if (ch == 'D') newX++; // move down
if (newX >= 0 && newX < m && newY >= 0 && newY < m) {
x = newX;
y = newY;
}
}
[Link](x + " " + y);
}
}
Josephus Trap :
import [Link].*;
class Main {
static int josephus(int n, int k)
{
if (n == 1)
return 1;
else
return (josephus(n - 1, k) + k - 1) % n + 1;
}
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int n = [Link]();
int k = [Link]();
[Link](josephus(n, k));
}
}
Combinations:
import [Link].*;
public class EthCode {
static void combinationUtil(int arr[], int n, int r, int index,int data[], int i)
{
if (index == r)
{
for (int j=0; j<r; j++)
[Link](data[j]+" "); [Link]("");
return;
}
if (i >= n)
return;
data[index] = arr[i];
combinationUtil(arr, n, r, index+1, data, i+1);
combinationUtil(arr, n, r, index, data, i+1);
}
static void printCombination(int arr[], int n, int r)
{
int data[]=new int[r];
combinationUtil(arr, n, r, 0, data, 0);
}
public static void main (String[] args) {
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = [Link];
printCombination(arr, n, r);
}
}

Booth's algorithm

import [Link].*;

class Main

static int solve(int a, int b)

return a*b;

public static void main(String[] args)

Scanner sc = new Scanner([Link]);

int a = [Link]();

int b = [Link]();

[Link](solve(a,b));

You might also like