Edited Prct

11
Chinese-Remainder-Theorem public class CRT { /* * performs the Euclidean algorithm on a and b to find a pair of coefficients * (stored in the output array) that correspond to x and y in the equation * ax + by = gcd(a,b) * constraint: a > b */ public static int[] euclidean(int a, int b) { if(b > a) { //reverse the order of inputs, run through this method, then reverse outputs int[] coeffs = euclidean(b, a); int[] output = {coeffs[1], coeffs[0]}; return output; } int q = a/b; //a = q*b + r --> r = a - q*b int r = a -q*b; //when there is no remainder, we have reached the gcd and are done if(r == 0) { int[] output = {0, 1}; return output; } //call the next iteration down (b = qr + r_2) int[] next = euclidean(b, r); int[] output = {next[1], next[0] - q*next[1]}; return output; } //finds the least positive integer equivalent to a mod m public static int leastPosEquiv(int a, int m) { //a eqivalent to b mod -m <==> a equivalent to b mod m if(m < 0) return leastPosEquiv(a, -1*m);

Transcript of Edited Prct

Page 1: Edited Prct

Chinese-Remainder-Theorem

public class CRT{  /* * performs the Euclidean algorithm on a and b to find a pair of coefficients * (stored in the output array) that correspond to x and y in the equation * ax + by = gcd(a,b) * constraint: a > b */  public static int[] euclidean(int a, int b)  {    if(b > a)    {      //reverse the order of inputs, run through this method, then reverse outputs      int[] coeffs = euclidean(b, a);      int[] output = {coeffs[1], coeffs[0]};      return output;    }

    int q = a/b;    //a = q*b + r --> r = a - q*b    int r = a -q*b;        //when there is no remainder, we have reached the gcd and are done    if(r == 0)    {      int[] output = {0, 1};      return output;    }        //call the next iteration down (b = qr + r_2)    int[] next = euclidean(b, r);        int[] output = {next[1], next[0] - q*next[1]};    return output;  }    //finds the least positive integer equivalent to a mod m  public static int leastPosEquiv(int a, int m)  {    //a eqivalent to b mod -m <==> a equivalent to b mod m    if(m < 0)      return leastPosEquiv(a, -1*m);    //if 0 <= a < m, then a is the least positive integer equivalent to a mod m    if(a >= 0 && a < m)      return a;        //for negative a, find the least negative integer equivalent to a mod m    //then add m    if(a < 0)      return -1*leastPosEquiv(-1*a, m) + m;    

Page 2: Edited Prct

    //the only case left is that of a,m > 0 and a >= m        //take the remainder according to the Division algorithm    int q = a/m;        /* * a = qm + r, with 0 <= r < m * r = a - qm is equivalent to a mod m * and is the least such non-negative number (since r < m) */    return a - q*m;  }    public static void main(String[] args)  {

/* * the current setup finds a number x such that: * x = 2 mod 5, x = 3 mod 7, x = 4 mod 9, and x = 5 mod 11 * note that the values in mods must be mutually prime */

    int[] constraints = {2,3,4,5}; //put modular contraints here    int[] mods = {5,7,9,11}; //put moduli here        //M is the product of the mods    int M = 1;    for(int i = 0; i < mods.length; i++)      M *= mods[i];        int[] multInv = new int[constraints.length];        /* * this loop applies the Euclidean algorithm to each pair of M/mods[i] and mods[i] * since it is assumed that the various mods[i] are pairwise coprime, * the end result of applying the Euclidean algorithm will be * gcd(M/mods[i], mods[i]) = 1 = a(M/mods[i]) + b(mods[i]), or that a(M/mods[i]) is * equivalent to 1 mod (mods[i]). This a is then the multiplicative * inverse of (M/mods[i]) mod mods[i], which is what we are looking to multiply * by our constraint constraints[i] as per the Chinese Remainder Theorem * euclidean(M/mods[i], mods[i])[0] returns the coefficient a * in the equation a(M/mods[i]) + b(mods[i]) = 1 */    for(int i = 0; i < multInv.length; i++)      multInv[i] = euclidean(M/mods[i], mods[i])[0];        int x = 0;        //x = the sum over all given i of (M/mods[i])(constraints[i])(multInv[i])    for(int i = 0; i < mods.length; i++)      x += (M/mods[i])*constraints[i]*multInv[i];        x = leastPosEquiv(x, M);        System.out.println("x is equivalent to " + x + " mod " + M);  }}

Page 3: Edited Prct

Bellman-Ford Algorithm

import java.util.Scanner; public class BellmanFord{

private int distances[]; private int numberofvertices; public static final int MAX_VALUE = 999;  public BellmanFord(int numberofvertices) { this.numberofvertices = numberofvertices; distances = new int[numberofvertices + 1]; }  public void BellmanFordEvaluation(int source, int adjacencymatrix[][]) { for (int node = 1; node <= numberofvertices; node++) { distances[node] = MAX_VALUE; }  distances[source] = 0; for (int node = 1; node <= numberofvertices - 1; node++) { for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) { for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) { if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE) { if (distances[destinationnode] > distances[sourcenode] + adjacencymatrix[sourcenode][destinationnode]) distances[destinationnode] = distances[sourcenode] + adjacencymatrix[sourcenode][destinationnode]; } } } }  for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) { for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) {

Page 4: Edited Prct

if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE) { if (distances[destinationnode] > distances[sourcenode] + adjacencymatrix[sourcenode][destinationnode]) System.out.println("The Graph contains negative egde cycle"); } } }  for (int vertex = 1; vertex <= numberofvertices; vertex++) { System.out.println("distance of source " + source + " to " + vertex + " is " + distances[vertex]); } }  public static void main(String... arg) { int numberofvertices = 0; int source; Scanner scanner = new Scanner(System.in);  System.out.println("Enter the number of vertices"); numberofvertices = scanner.nextInt();  int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices + 1]; System.out.println("Enter the adjacency matrix"); for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) { for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) { adjacencymatrix[sourcenode][destinationnode] = scanner.nextInt(); if (sourcenode == destinationnode) { adjacencymatrix[sourcenode][destinationnode] = 0; continue; } if (adjacencymatrix[sourcenode][destinationnode] == 0) { adjacencymatrix[sourcenode][destinationnode] = MAX_VALUE; } } }  System.out.println("Enter the source vertex"); source = scanner.nextInt();  BellmanFord bellmanford = new BellmanFord(numberofvertices);

Page 5: Edited Prct

bellmanford.BellmanFordEvaluation(source, adjacencymatrix); scanner.close(); }}

Output:

$javac BellmanFord.java$java BellmanFord Enter the number of vertices6Enter the adjacency matrix0 4 0 0 -1 00 0 -1 0 -2 00 0 0 0 0 0 0 0 0 0 0 00 0 0 -5 0 30 0 0 0 0 0 Enter the source vertex1 distance of source 1 to 1 is 0distance of source 1 to 2 is 4distance of source 1 to 3 is 3distance of source 1 to 4 is -6distance of source 1 to 5 is -1distance of source 1 to 6 is 2

Page 6: Edited Prct

Kapsack Algorithm

import java.util.Scanner; /** Class Knapsack **/public class Knapsack{ public void solve(int[] wt, int[] val, int W, int N) { int NEGATIVE_INFINITY = Integer.MIN_VALUE; int[][] m = new int[N + 1][W + 1]; int[][] sol = new int[N + 1][W + 1];  for (int i = 1; i <= N; i++) { for (int j = 0; j <= W; j++) { int m1 = m[i - 1][j]; int m2 = NEGATIVE_INFINITY; if (j >= wt[i]) m2 = m[i - 1][j - wt[i]] + val[i]; /** select max of m1, m2 **/ m[i][j] = Math.max(m1, m2); sol[i][j] = m2 > m1 ? 1 : 0; } } /** make list of what all items to finally select **/ int[] selected = new int[N + 1]; for (int n = N, w = W; n > 0; n--) { if (sol[n][w] != 0) { selected[n] = 1; w = w - wt[n]; } else selected[n] = 0; } /** Print finally selected items **/ System.out.println("\nItems selected : "); for (int i = 1; i < N + 1; i++) if (selected[i] == 1) System.out.print(i +" "); System.out.println(); } /** Main function **/ public static void main (String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Knapsack Algorithm Test\n"); /** Make an object of Knapsack class **/ Knapsack ks = new Knapsack();  System.out.println("Enter number of elements "); int n = scan.nextInt(); 

Page 7: Edited Prct

int[] wt = new int[n + 1]; int[] val = new int[n + 1];  System.out.println("\nEnter weight for "+ n +" elements"); for (int i = 1; i <= n; i++) wt[i] = scan.nextInt(); System.out.println("\nEnter value for "+ n +" elements"); for (int i = 1; i <= n; i++) val[i] = scan.nextInt();  System.out.println("\nEnter knapsack weight "); int W = scan.nextInt();  ks.solve(wt, val, W, n); }}

Output:

Knapsack Algorithm Test Enter number of elements5 Enter weight for 5 elements50 10 20 40 30 Enter value for 5 elements300 60 90 100 240 Enter knapsack weight60 Items selected :2 3 5

Page 8: Edited Prct

Miller Rabin Primality Test Algorithm import java.util.Scanner;import java.util.Random;import java.math.BigInteger; /** Class MillerRabin **/public class MillerRabin{ /** Function to check if prime or not **/ public boolean isPrime(long n, int iteration) { /** base case **/ if (n == 0 || n == 1) return false; /** base case - 2 is prime **/ if (n == 2) return true; /** an even number other than 2 is composite **/ if (n % 2 == 0) return false;  long s = n - 1; while (s % 2 == 0) s /= 2;  Random rand = new Random(); for (int i = 0; i < iteration; i++) { long r = Math.abs(rand.nextLong()); long a = r % (n - 1) + 1, temp = s; long mod = modPow(a, temp, n); while (temp != n - 1 && mod != 1 && mod != n - 1) { mod = mulMod(mod, mod, n); temp *= 2; } if (mod != n - 1 && temp % 2 == 0) return false; } return true; } /** Function to calculate (a ^ b) % c **/ public long modPow(long a, long b, long c) { long res = 1; for (int i = 0; i < b; i++) { res *= a; res %= c; } return res % c; } /** Function to calculate (a * b) % c **/ public long mulMod(long a, long b, long mod) {

Page 9: Edited Prct

return BigInteger.valueOf(a).multiply(BigInteger.valueOf(b)).mod(BigInteger.valueOf(mod)).longValue(); } /** Main function **/ public static void main (String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Miller Rabin Primality Algorithm Test\n"); /** Make an object of MillerRabin class **/ MillerRabin mr = new MillerRabin(); /** Accept number **/ System.out.println("Enter number\n"); long num = scan.nextLong(); /** Accept number of iterations **/ System.out.println("\nEnter number of iterations"); int k = scan.nextInt(); /** check if prime **/ boolean prime = mr.isPrime(num, k); if (prime) System.out.println("\n"+ num +" is prime"); else System.out.println("\n"+ num +" is composite");  }}

Output:

Miller Rabin Primality Algorithm Test Enter number 5510389 Enter number of iterations2 5510389 is prime