filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.hs
fibonacci :: Int -> Int fibonacci 0 = 0 fibonacci 1 = 1 fibonacci n = (fibonacci (n-1))+(fibonacci (n-2))
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.java
// Part of Cosmos by OpenGenus Foundation public class fibonacci { public static long fibonacciTerm(int term){ return calculateFibonacci(term - 2, 1, 1); } public static long calculateFibonacci(int a, int b, int c){ if(a <= 0){ return c; } return calculateFibonacci(a - 1, c, c + b); } }
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.js
function fibonacci(n) { if (n <= 1) { return n; } else { return fibonacci(n - 2) + fibonacci(n - 1); } } function memoizedFibonacci(n, cache = { 0: 0, 1: 1 }) { if (!(n in cache)) { cache[n] = memoizedFibonacci(n - 2, cache) + memoizedFibonacci(n - 1, cache); } return cache[n]; } fibonacci(18); // 2584 memoizedFibonacci(20); // 6765
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.kt
/* * Part of Cosmos by OpenGenus Foundation */ fun fibonacci(number: Int): Int { if (number <= 1) { return number; } return fibonacci(number - 2) + fibonacci(number -1); } fun main() { println(fibonacci(1)); // 1 println(fibonacci(2)); // 1 println(fibonacci(4)); // 3 println(fibonacci(8)); // 21 println(fibonacci(16)); // 987 }
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.php
<?php /** * Part of Cosmos by OpenGenus Foundation * * @param int $n * * @return integer */ function fibonacci($n) { return round(((5 ** .5 + 1) / 2) ** $n / 5 ** .5); } echo sprintf('Fibonacci of %d is %d.', $number = 10, fibonacci($number));
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.py
import sys def fibonacci(n): if n < 2: return n return fibonacci(n - 2) + fibonacci(n - 1) def fibonacci_memoized(n): cache = {0: 0, 1: 1} def fib(n): if n not in cache: cache[n] = fib(n - 2) + fib(n - 1) return cache[n] return fib(n) x = int(sys.argv[1]) print(fibonacci_memoized(x))
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.rb
def fibonacci(n) case n when 0 then 0 when 1 then 1 else fibonacci(n - 2) + fibonacci(n - 1) end end def fibonacci_memoized(n, cache = nil) cache ||= { 0 => 0, 1 => 1 } cache[n] = fibonacci_memoized(n - 2, cache) + fibonacci_memoized(n - 1, cache) unless cache.key?(n) cache.fetch(n) end n = ARGV[0].to_i puts fibonacci_memoized(n)
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.rs
// Rerturns the nth element of the fibonacci sequence fn fibo(n :i64) -> i64 { match n { 0 => 0, 1 => 1, _ => (fibo(n-1) + fibo(n-2)) } } fn main() { println!("{}",fibo(30)); println!("{}",fibo(10)); println!("{}",fibo(8)); println!("{}",fibo(5)); println!("{}",fibo(2)); }
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.scala
// 0 and 1 are the first two numbers in the sequence, //so we start the accumulators with 0,1. // At every iteration, we add the two numbers to get the next one. // Path of Cosmos by OpenGenus Foundation //returns nth fibonacci number def fib(n: Int): Int = { @annotation.tailrec//makes sure loop() is tail recursive def loop(n: Int, prev: Int, cur: Int): Int = if (n == 0) prev else loop(n - 1, cur, prev + cur) loop(n, 0, 1) } //to test //println(fib(6))
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.swift
// Part of Cosmos by OpenGenus Foundation func fibonacciTerm(n: Int) -> Int { return calcFibonacci(a: n - 2, b: 1, c: 1) } func calcFibonacci(a: Int, b: Int, c: Int) -> Int { if a <= 0 { return c } return calcFibonacci(a: a - 1, b: c, c: c + b) }
code/mathematical_algorithms/src/fractals/julia_miim.cpp
// This is a simple code to generate Julia sets of quadratic functions // of the form f(z) = z^2 + c. // // The algorithm used is the Modified Inverse Iteration Method described in // // Heinz-Otto Peitgen, Dietmar Saupe, eds., The Science of Fractal Images // Springer-Verlag, New York, 1988. pp. 178 // ISBN 0-387-96608-0 // #include <iostream> #include <cassert> #include <cmath> #include <vector> using namespace std; double randUnit() { return ((double)rand()) / RAND_MAX; } double randInterval(double a, double b) { return a + (b - a) * randUnit(); } void inverseStep(double wx, double wy, vector< vector<int>>& grid, const double cx, const double cy, const int Nmax, const int res, const int depth, const int maxdepth) { // Check for end of recursion if (depth >= maxdepth) return; // This point is good, so write it out cout << wx << ' ' << wy << endl; double r, theta; int xneg, yneg, xpos, ypos; // grid coordinates // convert to polar coordinates r = sqrt((wx - cx) * (wx - cx) + (wy - cy) * (wy - cy)); theta = atan2(wy - cy, wx - cx); // find inverse using f^(-1)(w) = +/-sqrt(w - c) wx = sqrt(r) * cos(theta / 2.0); wy = sqrt(r) * sin(theta / 2.0); // translate complex plane coordinates to grid coordinates xpos = static_cast<int>(floor( (res * (wx + 2.0)) / 4.0) ); ypos = static_cast<int>(floor( (res * (wy + 2.0)) / 4.0) ); xneg = static_cast<int>(floor( (res * (-wx + 2.0)) / 4.0) ); yneg = static_cast<int>(floor( (res * (-wy + 2.0)) / 4.0) ); if (grid[xpos][ypos] < Nmax) { grid[xpos][ypos]++; inverseStep(wx, wy, grid, cx, cy, Nmax, res, depth + 1, maxdepth); } if (grid[xneg][yneg] < Nmax) { grid[xneg][yneg]++; inverseStep(-wx, -wy, grid, cx, cy, Nmax, res, depth + 1, maxdepth); } } int main() { double cx, cy; // real and imaginary parts of c parameter double wx, wy; // real and imaginary parts of iterated value int Nmax; // max number of points per grid box int res; // resolution of the grid int maxdepth; // maximum depth of tree search srand(time(NULL)); // seed the random number generator with the system clock cin >> cx >> cy >> Nmax >> res >> maxdepth; assert(Nmax > 0); assert(res >= 10); assert((res % 2) == 0); assert(maxdepth > 0); // The grid ranges from -2...+2 in both the x and y directions vector< vector<int>> grid; vector<int> empty_row(res, 0); for (int i = 0; i < res; ++i) grid.push_back(empty_row); // Randomly pick a point somewhat near the origin with which // to start iterating. wx = randInterval(-1.0, 1.0); wy = randInterval(-1.0, 1.0); double r, theta; double sign; int xneg, yneg, xpos, ypos; // grid coordinates // Quickly do some iterations randomly picking one of the roots so // that we get close to J_c before selectively picking roots. int i = 0; while (i < 50) { // original function f(z) = z^2 + c // inverse function f^(-1)(w) = +/-sqrt(w - c) r = sqrt((wx - cx) * (wx - cx) + (wy - cy) * (wy - cy)); theta = atan2(wy - cy, wx - cx); sign = (randUnit() < 0.5) ? -1.0 : 1.0; wx = sign * sqrt(r) * cos(theta / 2.0); wy = sign * sqrt(r) * sin(theta / 2.0); ++i; } xpos = static_cast<int>(floor( (res * (wx + 2.0)) / 4.0) ); ypos = static_cast<int>(floor( (res * (wy + 2.0)) / 4.0) ); xneg = static_cast<int>(floor( (res * (-wx + 2.0)) / 4.0) ); yneg = static_cast<int>(floor( (res * (-wy + 2.0)) / 4.0) ); grid[xpos][ypos]++; inverseStep(wx, wy, grid, cx, cy, Nmax, res, 0, maxdepth); grid[xneg][yneg]++; inverseStep(-wx, -wy, grid, cx, cy, Nmax, res, 0, maxdepth); return 0; }
code/mathematical_algorithms/src/fractals/simple_julia.cpp
#include <iostream> #include <cassert> #include <cmath> using namespace std; // This is a simple code to generate Julia sets of quadratic functions // such as f(z) = z^2 + c. // // The algorithm used is the backwards iteration algorithm with each root // weighted equally. (Note: This algorithm often misses a good portion // of the Julia set. It is simply included as a reference.) double randUnit() { return ((double)rand()) / RAND_MAX; } double randInterval(double a, double b) { return a + (b - a) * randUnit(); } int main() { double cx, cy; // real and imaginary parts of c parameter double wx, wy; // real and imaginary parts of iterated value int N; // number of iterations to perform // seed the random number generator with the system clock srand(time(NULL)); cin >> cx >> cy >> N; assert(N > 0); // Randomly pick a point somewhat near the origin with which // to start iterating. wx = randInterval(-1.0, 1.0); wy = randInterval(-1.0, 1.0); double r, theta; double sign = 1.0; for (int i = 0; i <= N; ++i) { // original function f(z) = z^2 + c // inverse function f^(-1)(w) = +/-sqrt(w - c) r = sqrt((wx - cx) * (wx - cx) + (wy - cy) * (wy - cy)); theta = atan2(wy - cy, wx - cx); sign = randInterval(-1.0, 1.0) < 0 ? -1.0 : 1.0; wx = sign * sqrt(r) * cos(theta / 2.0); wy = sign * sqrt(r) * sin(theta / 2.0); // skip the first 100 iterations because they are not accurate if (i > 99) cout << wx << ' ' << wy << '\n'; } return 0; }
code/mathematical_algorithms/src/gaussian_elimination/gaussian_elimination.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <cmath> #include <iostream> #include <vector> using namespace std; const long double EPS = 1e-8; /** * Gaussian elimination (also known as row reduction). Solves systems of linear equations. * * @param a is an input matrix * @param ans is result vector * @return number of system solutions (0 or 1), -1 if the system is inconsistent. */ int gauss(vector<vector <long double>> a, vector<long double> &ans) { int n = (int) a.size(); int m = (int) a[0].size() - 1; vector<int> cged(m, -1); ans.assign(m, 0); for (int cur_col = 0, cur_row = 0; cur_col < m && cur_row < n; cur_col++) { int sel = cur_row; for (int i = cur_row; i < n; i++) if (abs(a[i][cur_col]) > abs(a[sel][cur_col])) sel = i; if (abs(a[sel][cur_col]) < EPS) continue; swap(a[sel], a[cur_row]); cged[cur_col] = cur_row; for (int i = 0; i < n; i++) if (i != cur_row) { long double cf = -a[i][cur_col] / a[cur_row][cur_col]; for (int j = cur_col; j <= m; j++) a[i][j] += a[cur_row][j] * cf; } cur_row++; } for (int i = 0; i < m; i++) if (cged[i] != -1) ans[i] = a[cged[i]][m] / a[cged[i]][i]; for (int i = 0; i < n; i++) { long double sum = 0.0; for (int j = 0; j < m; j++) sum += ans[j] * a[i][j]; if (abs(sum - a[i][m]) > EPS) return 0; } for (int i = 0; i < m; i++) if (cged[i] == -1) return -1; return 1; } /* * Input: * 2 * 2 1 4 * 1 2 5 * Output: * single * 1 2 */ int main() { int n; cin >> n; vector <vector <long double>> l(n); vector <long double> ans(n); for (int i = 0; i < n; i++) { l[i].resize(n + 1); for (int j = 0; j <= n; j++) cin >> l[i][j]; } int st = gauss(l, ans); if (!(st + 1)) { cout << "infinity\n"; return 0; } if (!st) { cout << "impossible\n"; return 0; } cout << "single\n"; for (int i = 0; i < n; i++) cout << ans[i] << " "; cout << "\n"; }
code/mathematical_algorithms/src/gaussian_elimination/gaussian_elimination.java
public class GaussianElimination { int rows; int cols; double[][] matrix; public GaussianElimination(double[][] matrix) { if (matrix == null) { throw new NullPointerException("matrix cannot be null"); } this.rows = matrix.length; this.cols = matrix[0].length; this.matrix = new double[rows][cols]; copyMatrix(this.matrix, matrix); } /*Row reduces our rows*cols=rows*(n+1) matrix into row reduced echelon form with Gaussian elimination. Where our matrix is a system of m equations with n variables.*/ private void gaussianEliminate() { for (int i = 0; i < (cols - 1); i++) { System.out.println("Outer loop number: " + i); if (matrix[i][i] == 0) { boolean restColZero = true; int firstNonzeroRow = i; for (int ip = i; i < rows; ip++) { if (matrix[ip][i] != 0) { restColZero = false; firstNonzeroRow = ip; break; } } if (restColZero) { continue; } else { swapRows(matrix, i, firstNonzeroRow); System.out.println("Swapping rows " + i + " and " + firstNonzeroRow); } } double divider = matrix[i][i]; System.out.println("Dividing row " + i + " by " + divider); printArray(matrix); for (int ip = 0; ip < (cols); ip++) { //Rounding for beautiful output but accuracy -0.1 double temp = matrix[i][ip] / divider; double q = new BigDecimal(temp).setScale(1, RoundingMode.HALF_DOWN).doubleValue(); matrix[i][ip] = q; } for (int k = i + 1; k < rows; k++) { System.out.println("Subtracting " + matrix[k][i] + " times row " + i + " from row " + k); scaleSubtract(matrix, matrix[i], k, matrix[k][i]); printArray(matrix); } } System.out.println("Starting back substitution"); for (int u = cols - 2; u >= 0; u--) { if (matrix[u][u] != 0) { for (int v = u - 1; v >= 0; v--) { scaleSubtract(matrix, matrix[u], v, matrix[v][u]); System.out.println("Subtracting " + matrix[v][u] + " times row " + u + " from row " + v); printArray(matrix); } } } } /*Copies matrix b into matrix a*/ private void copyMatrix(double[][] a, double[][] b) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { a[i][j] = b[i][j]; } } } /*Swaps the rows rowNum and rowNump in a*/ private void swapRows(double[][] a, int rowNum, int rowNump) { for (int i = 0; i < a.length; i++) { double temp = a[rowNum][i]; a[rowNum][i] = a[rowNump][i]; a[rowNump][i] = temp; } } /*Subtracts an array as a row from a at rowNum, with the array multiplied by factor*/ private void scaleSubtract(double[][] a, double[] row, int rowNum, double factor) { for (int i = 0; i < cols; i++) { //Rounding for beautiful output but accuracy -0.1 double temp = a[rowNum][i] - (row[i] * factor); double q = new BigDecimal(temp).setScale(1, RoundingMode.HALF_DOWN).doubleValue(); a[rowNum][i] = q; } } public void printArray(double[][] arr) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); } public static void main(String[] args) { double[][] myMatrix = {{3.0, 2.0, -5.0, -1.0}, {2.0, -1.0, 3.0, 13.0}, {1.0, 2.0, -1.0, 9.0}}; GaussianElimination reducer = new GaussianElimination(myMatrix); System.out.println("Original matrix: "); reducer.printArray(reducer.matrix); reducer.gaussianEliminate(); System.out.println("Result matrix: "); reducer.printArray(reducer.matrix); } }
code/mathematical_algorithms/src/gaussian_elimination/scala/build.sbt
name := "gaussian-elimination" version := "0.1" scalaVersion := "2.11.1"
code/mathematical_algorithms/src/gaussian_elimination/scala/project/build.properties
sbt.version = 1.1.1
code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/gaussianelimination.scala
package gaussian.elimination import structures.{Epsilon, Matrix, RegularMatrix} import scala.annotation.tailrec object GaussianElimination { def startAlgorithm(matrix: Matrix[Double], b: List[Double], epsilon: Epsilon): Solution = { def isPivotNotNull(currentColumn: Int, matrix: Matrix[Double]): Boolean = Math.abs(matrix.rows(currentColumn).max) > epsilon.toNegative10 @tailrec def gaussianElimination(currentColumn: Int, matrix: Matrix[Double], b: List[Double]): Solution = { //getting coefficients of the division val coefficients = for { row <- matrix.rows.drop(currentColumn + 1) currentRow = matrix.rows(currentColumn) coefficient = row(currentColumn) / currentRow(currentColumn) } yield coefficient val transformedMatrix = transformMatrix(currentColumn, matrix, coefficients, epsilon) val transformedB = transformB(currentColumn, b, coefficients, epsilon) val nextColumn = currentColumn + 1 if (nextColumn > matrix.N - 1 && isPivotNotNull(nextColumn, matrix)) Solution(matrix, b, currentColumn, epsilon) else { val pivot = transformedMatrix.maxByColumn(nextColumn) val pivotFirstMatrix = transformedMatrix.swapRows(nextColumn, pivot) val pivotFirstB = swapElements(transformedB, nextColumn, pivot) if(nextColumn == matrix.N - 1) Solution(pivotFirstMatrix, pivotFirstB, nextColumn, epsilon) else gaussianElimination(nextColumn, pivotFirstMatrix, pivotFirstB) } } val pivot = matrix.maxByColumn(0) val pivotFirstMatrix = matrix.swapRows(0, pivot) val pivotFirstB = swapElements(b, 0, pivot) gaussianElimination(0, pivotFirstMatrix, pivotFirstB) } private def transformB(currentColumn: Int, b: List[Double], coefficients: List[Double], epsilon: Epsilon): List[Double] = b.slice(0, currentColumn + 1) ::: b.slice(currentColumn + 1, b.length) .zip(coefficients) .map(p => truncate(p._1 - (b(currentColumn) * p._2), epsilon)) private def transformMatrix(currentColumn: Int, matrix: Matrix[Double], coefficients: List[Double], epsilon: Epsilon): Matrix[Double] = { //rows from which matrix's rows will be subtracted from val rowsForSubtraction = coefficients.map(c => matrix.rows(currentColumn).map(_ * c)) RegularMatrix( matrix.rows.slice(0, currentColumn + 1) //first slice which remains unchanged //zipping with rows which will be subtracted from one another //TODO maybe beautiful version ? ::: matrix.rows.slice(currentColumn + 1, matrix.N).zip(rowsForSubtraction).map { pair => //zipping elements of the rows pair._1.zip(pair._2).map(p => truncate(p._1 - p._2, epsilon)) }) } private def swapElements[A: Fractional](list: List[A], first: Int, second: Int): List[A] = { def inBoundaries(i: Int): Boolean = i >= 0 && i < list.length require(inBoundaries(first) && inBoundaries(second)) if(first < second) list.updated(first, list(second)).updated(second, list(first)) else list } private def truncate(a: Double, epsilon: Epsilon): Double = { Math.floor(a * epsilon.decimalsPower) / epsilon.decimalsPower } }
code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/matrixtype.scala
package gaussian.elimination trait MatrixType case object Singular extends MatrixType case object NotSingular extends MatrixType
code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/solution.scala
package gaussian.elimination import structures.{Epsilon, Matrix} case class Solution(matrix: Matrix[Double], b: List[Double], lastPivot: Int, epsilon: Epsilon) { def isSingular: MatrixType = { val det = (0 until matrix.M).foldRight(1.0)((curr, acc) => matrix.rows(curr)(curr) * acc) if( det != 0 ) NotSingular else Singular } def solve(): Option[List[Double]] = { isSingular match { case Singular => None case NotSingular => Some(solveSystem()) } } private def solveSystem(): List[Double] = { /* 1 2 3 4 5 0 1 2 3 4 0 0 1 2 3 0 0 0 1 2 0 0 0 0 1 => 0 0 0 0 1 0 0 0 1 2 0 0 1 2 3 0 1 2 3 4 1 2 3 4 5 */ /* 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 */ val removedZeroes = matrix.rows.map(r => r.dropWhile(_ == 0.0)).reverse val zippedWithB = removedZeroes.zip(b.reverse) val result = zippedWithB.foldLeft(List.empty[Double]) { (acc, curr) => val result = curr._2 val coefficient = curr._1.head val restOfEquation = curr._1.tail val leftSideSum = restOfEquation.zip(acc).foldRight(0.0) { (curr, acc) => acc + curr._1 * curr._2 } epsilon.truncate((result - leftSideSum) / coefficient) +: acc } result } }
code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/main.scala
import gaussian.elimination.GaussianElimination import structures.{Epsilon, RegularMatrix} object Main extends App { val matrixTest = RegularMatrix[Double](List( List[Double](0.02, 0.01, 0, 0), List[Double](1.0, 2, 1, 0), List[Double](0, 1, 2, 1), List[Double](0, 0, 100, 200) )) // example from // http://web.mit.edu/10.001/Web/Course_Notes/GaussElimPivoting.html val matrixTest2 = RegularMatrix[Double]((0.0 until 100.0 by 1.0).toList.map(i => (0.0 until 100.0 by 1.0).toList)) val b2 = (100.0 until 0.0 by -1.0).toList val b = List[Double](0.02, 1, 4, 800) val solution = GaussianElimination.startAlgorithm(matrixTest, b, Epsilon(6)) println(solution.matrix) solution.solve() match { case None => println("No solution") case Some(result) => println(result) } //println(GaussianElimination.startAlgorithm(matrixTest2, b, Epsilon(3))) //(0 until matrixTest.N).map(matrixTest.maxByColumn).foreach(println) }
code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/epsilon.scala
package structures case class Epsilon(precision: Int) { require(precision > 0 && precision < 16) def apply(coefficients: List[Double]) = { coefficients.map(c => Math.floor(c * this.decimalsPower) / this.decimalsPower) } def truncate(a: Double): Double = { Math.floor(a * this.decimalsPower) / this.decimalsPower } val decimalsPower: Double = Math.pow(10, precision) val toNegative10: Double = Math.pow(10, - precision) }
code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/matrix.scala
package structures trait Matrix[A] { def rows: List[List[A]] def rowLength: Int def N: Int def M: Int def +++(other: Matrix[A])(implicit n: Fractional[A]): Matrix[A] def ---(other: Matrix[A])(implicit n: Fractional[A]): Matrix[A] def ***(other: Matrix[A]): Matrix[A] def map[B](f: A => B)(implicit n: Fractional[B]): Matrix[B] def mapRows[B](f: List[A] => List[B])(implicit n: Fractional[B]): Matrix[B] def swapRows(first: Int, second: Int): Matrix[A] def maxByColumn(columnIndex: Int): Int }
code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/regularmatrix.scala
package structures case class RegularMatrix[A: Fractional](rows: List[List[A]]) extends Matrix[A] { require(this.rows.forall(_.length == this.rows.maxBy(_.length).length)) override def rowLength: Int = this.rows.head.length override def N: Int = this.rows.length override def M: Int = this.rowLength override def +++(other: Matrix[A])(implicit n: Fractional[A]): Matrix[A] = { require(this.rowLength == other.rowLength) applyOperation(other, n.plus) } override def ---(other: Matrix[A])(implicit n: Fractional[A]): Matrix[A] = { require(this.rowLength == other.rowLength) applyOperation(other, n.minus) } private def applyOperation(other: Matrix[A], f: (A, A) => A): Matrix[A] = { RegularMatrix[A](this.rows, other, f) } override def map[B](f: A => B)(implicit n: Fractional[B]): RegularMatrix[B] = RegularMatrix(this.rows.map(_.map(f)))(n) override def mapRows[B](f: List[A] => List[B])(implicit n: Fractional[B]): RegularMatrix[B] = RegularMatrix(this.rows.map(f))(n) override def swapRows(first: Int, second: Int): Matrix[A] = { require(RegularMatrix.isInBoundaries(first, N) && RegularMatrix.isInBoundaries(second, N)) if (first == second || first > second) this else { RegularMatrix( this.rows.slice(0, first) ::: List(this.rows(second)) ::: this.rows.slice(first + 1, second) ::: List(this.rows(first)) ::: this.rows.slice(second + 1, this.N)) } } override def maxByColumn(columnIndex: Int): Int = this.rows.zipWithIndex.slice(columnIndex, this.N).maxBy { column => val n = implicitly[Numeric[A]] n.abs(column._1(columnIndex)) }._2 override def ***(other: Matrix[A]): Matrix[A] = { type ValueWithIndex = (A, Int) val m = implicitly[Fractional[A]] def updateSum(sumSoFar: A, currElement: ValueWithIndex, currIndex: Int): A = m.plus(sumSoFar, m.times(currElement._1, other.rows(currElement._2)(currIndex))) def splitIntoRows(values: List[A], rowLength: Int): List[List[A]] = { require(values.length % rowLength == 0) if (values.isEmpty) List.empty else values.slice(0, rowLength) :: splitIntoRows(values.drop(rowLength), rowLength) } def computeUpdatedValueForCurrentPosition(l: List[(A, Int)], currIndex: Int) = l.foldRight(m.zero) { (curr, acc) => updateSum(acc, curr, currIndex) } val productStream: List[A] = for { row <- this.rows currIndex <- row.indices.toList elementsWithIndex = row.zipWithIndex valueForCurrentPosition = computeUpdatedValueForCurrentPosition(elementsWithIndex, currIndex) } yield valueForCurrentPosition new RegularMatrix[A](splitIntoRows(productStream, this.rows.head.length))(m) } } object RegularMatrix { def apply[A](rows: List[List[A]], other: Matrix[A], f: (A, A) => A)(implicit n: Fractional[A]): RegularMatrix[A] = new RegularMatrix(rows .zip(other.rows) .map { p => p._1.zip(p._2) .map(v => f(v._1, v._2)) } )(n) def isInBoundaries(row: Int, rowLength: Int): Boolean = { row >= 0 && row < rowLength } }
code/mathematical_algorithms/src/gcd_and_lcm/README.md
# LCM The Least Common Multiple (LCM) is also referred to as the Lowest Common Multiple (LCM) and Least Common Divisor (LCD). For two integers a and b, denoted LCM(a,b), the LCM is the smallest positive integer that is evenly divisible by both a and b. For example, LCM(2,3) = 6 and LCM(6,10) = 30. The LCM of two or more numbers is the smallest number that is evenly divisible by all numbers in the set. # GCD The greatest common factor (GCF or GCD or HCF) of a set of whole numbers is the largest positive integer that divides evenly into all numbers with zero remainder. For example, for the set of numbers 18, 30 and 42 the GCF = 6. <b>Greatest Common Factor of 0</b> Any non zero whole number times 0 equals 0 so it is true that every non zero whole number is a factor of 0. k × 0 = 0 so, 0 ÷ k = 0 for any whole number k. For example, 5 × 0 = 0 so it is true that 0 ÷ 5 = 0. In this example, 5 and 0 are factors of 0. GCF(5,0) = 5 and more generally GCF(k,0) = k for any whole number k. However, GCF(0, 0) is undefined.
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.c
/* Part of Cosmos by OpenGenus Foundation */ /* Created by Shubham Prasad Singh on 13/10/2017 */ /* GCD and LCM */ #include<stdio.h> int _gcd(int a, int b) ////////// Euclid Algorithm { if(!b) return (a); return (_gcd(b, a % b)); } int main() { int a, b; printf("Enter the numbers\n"); scanf("%d%d", &a, &b); int gcd = _gcd(a, b); int lcm = a * b / gcd; printf("GCD is %d\nLCM is %d \n", gcd, lcm); return (0); }
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.cpp
#include <stdio.h> #include <algorithm> // Part of Cosmos by OpenGenus Foundation int gcd(int x, int y) { while (y > 0) { x %= y; std::swap(x, y); } return x; } //should use this recursive approach. // int gcd(int c,int d) // { // if(d==0) // return a; // return gcd(d,c%d); // } int lcm(int x, int y) { return x / gcd(x, y) * y; } int main() { int a, b; scanf("%d %d", &a, &b); printf("GCD = %d\n", gcd(a, b)); printf("LCM = %d", lcm(a, b)); }
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.cs
using System; namespace gcd_and_lcm { class gcd_lcm { int a, b; public gcd_lcm(int number1,int number2) { a = number1; b = number2; } public int gcd() { int temp1 = a, temp2 = b; while (temp1 != temp2) { if (temp1 > temp2) { temp1 -= temp2; } else { temp2 -= temp1; } } return temp2; } public int lcm() { return a * b / gcd(); } } class Program { static void Main(string[] args) { int a = 20, b = 120; gcd_lcm obj = new gcd_lcm(a, b); Console.WriteLine("GCD of {0} and {1} is {2}", a, b, obj.gcd()); Console.WriteLine("LCM of {0} and {1} is {2}", a, b, obj.lcm()); Console.ReadKey(); } } }
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.erl
% Part of Cosmos by OpenGenus Foundation -module(gcd_and_lcm). -export([gcd/2, lcm/2]). gcd(X, 0) -> X; gcd(X, Y) -> gcd(Y, X rem Y). lcm(X, Y) -> X * Y / gcd(X, Y).
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.ex
# Part of Cosmos by OpenGenus Foundation defmodule GCDandLCM do def gcd(x, 0), do: x def gcd(x, y), do: gcd(y, rem(x, y)) def lcm(x, y), do: x * y / gcd(x, y) end
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.go
package main // Part of Cosmos by OpenGenus Foundation import ( "fmt" ) func calculateGCD(a, b int) int { for b != 0 { c := b b = a % b a = c } return a } func calculateLCM(a, b int, integers ...int) int { result := a * b / calculateGCD(a, b) for i := 0; i < len(integers); i++ { result = calculateLCM(result, integers[i]) } return result } func main() { // 8 fmt.Println(calculateGCD(8, 16)) // 4 fmt.Println(calculateGCD(8, 12)) // 12 fmt.Println(calculateLCM(3, 4)) // 1504 fmt.Println(calculateLCM(32, 94)) // 60 fmt.Println(calculateLCM(4, 5, 6)) // 840 fmt.Println(calculateLCM(4, 5, 6, 7, 8)) }
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.java
import java.util.*; // Part of Cosmos by OpenGenus Foundation class Gcd_Lcm_Calc{ public void determineLCM(int a, int b) { int num1, num2, lcm = 0; if (a > b) { num1 = a; num2 = b; } else { num1 = b; num2 = a; } for (int i = 1; i <= num2; i++) { if ((num1 * i) % num2 == 0) { lcm = num1 * i; System.out.println("LCM = " + lcm); break; } } } public int determineGCD(int a, int b) { while (b > 0) { int r = a % b; a = b; b = r; } return a; } public static void main(String[] args) { Gcd_Lcm_Calc obj = new Gcd_Lcm_Calc(); System.out.println("Enter two nos: "); Scanner s1 = new Scanner(System.in); int a = s1.nextInt(); int b = s1.nextInt(); obj.determineLCM(a, b); int gcd = obj.determineGCD(a, b); System.out.println("GCD = " + gcd); } }
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.js
function gcd(a, b) { return b === 0 ? a : gcd(b, a % b); } function lcm(a, b) { return b === 0 ? 0 : (a * b) / gcd(a, b); } // GCD console.log(gcd(15, 2)); // 1 console.log(gcd(144, 24)); // 24 // LCM console.log(lcm(12, 3)); // 12 console.log(lcm(27, 13)); // 351
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.php
<?php function gcd($a, $b) { if(!$b) { return $a; } return gcd($b, $a % $b); } function lcm($a, $b) { if($a || $b) { return 0; } return abs($a * $b) / gcd($a, $b); }
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.py
def gcd(a, b): while a > 0: b, a = a, b % a return b def lcm(a, b=None): if not b: assert len(a) >= 2 l = lcm(*a[:2]) for x in a[2:]: l = lcm(l, x) return l return int((a * b) / gcd(a, b)) if __name__ == "__main__": print(lcm([int(x) for x in input().split()]))
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.scala
object gcdandlcm extends App{ def gcd(a:Int, b:Int):Int = { while(b > 0){ val r:Int = a % b a = b b = r } a } def lcm(a:Int, b:Int):Int = { var num1:Int = 0 var num2:Int = 0 var lcm:Int = 0 if(a > b){ num1 = a num2 = b } else { num1 = b num2 = a } for(x <- 1 to num2){ if((num1 * i) % num2 == 0){ return num1 * i } } return 0 } }
code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm_best_approach.cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int #define FIO ios::sync_with_stdio(0); ll gcd(ll a,ll b) { while(a&&b) { if(a>b) a%=b; else b%=a; } return a+b; } ll lcm(ll a,ll b) { return (max(a,b)/gcd(a,b))*min(a,b); } int main() { FIO; ll number_a, number_b; cin >> number_a >> number_b; answer = lcm(number_a,number_b); cout << answer; return 0; }
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.c
#include<stdio.h> int greatest_digit(int n) { int max_digit = n % 10; while(n) { max_digit = (max_digit < n % 10) ? n % 10 : max_digit; n /= 10; } return (max_digit); } int main() { int n; scanf("%d", &n); printf("Greatest digit is %d :\n", greatest_digit(n)); return (0); }
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.cpp
#include <iostream> using namespace std; int greatest_digit(int n) { int max = 0; while (n != 0) { if (max < n % 10) max = n % 10; n /= 10; } return max; } int main() { int n; cin >> n; cout << greatest_digit(n); return 0; }
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.cs
/* Part of Cosmos by OpenGenus Foundation */ using System; namespace CS { public class GreatestDigitInNumber { static int GreatestDigit(int n) { int max = 0; while (n != 0) { if (max < n % 10) max = n % 10; n /= 10; } return max; } static void Main(string[] args) { var rand = new Random(); for (int i = 0; i <= 10; i++) { int number = rand.Next(65535); int digit = GreatestDigit(number); Console.WriteLine("Number: " + number + " \tGreatest Digit: " + digit); } } } }
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.hs
greatest :: Integer -> Integer greatest n | modOfTen == n = n | otherwise = modOfTen `max` greatest quotOfTen where modOfTen = mod n 10 quotOfTen = quot n 10
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.*; public class Greatest_digit_in_number{ public static void main(String args[]) { int num = 23238934; System.out.println(greatest_digit(num)); } // returns greatest digit in a given number public static int greatest_digit(int n) { int max = 0; while(n != 0) { if(max<n%10) max=n%10; n/=10; } return max; } }
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.js
function greatestDigit(num) { return String(num) .split("") .reduce((a, b) => Math.max(a, b)); } console.log(greatestDigit(123)); // 3 console.log(greatestDigit(321)); // 3 console.log(greatestDigit(12903)); // 9
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.php
<?php /** * Part of Cosmos by OpenGenus Foundation */ /** * Finds the greatest digit in number * * @param int $num number * @return int greatest digit */ function greatest_digit_in_number(int $num) { return max(array_map('intval', str_split($num))); } echo "greatest digit in number\n"; $test_data = [ [0, 0], [9, 9], [11, 1], [99, 9], [19, 9], [91, 9], [10000, 1], [1000090, 9], ]; foreach ($test_data as $test_case) { $input = $test_case[0]; $expected = $test_case[1]; $result = greatest_digit_in_number($input); printf( " input %d, expected %s, got %s: %s\n", $input, var_export($expected, true), var_export($result, true), ($expected === $result) ? 'OK' : 'FAIL' ); }
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.py
#!/usr/bin/python3 def greatest_digit(n): max_digit = int(n % 10) while n: if max_digit < n % 10: max_digit = n % 10 else: max_digit = max_digit n /= 10 return max_digit def greatest_digits_with_builtins(num): return int(max([*str(num)])) user_number = int(input("enter number: ")) print("greatest digit is :\n", int(greatest_digit(user_number))) print("greatest digit is :\n", greatest_digits_with_builtins(user_number))
code/mathematical_algorithms/src/greatest_digit_in_number/greatest_digit_in_number.rb
def greatest_digit_in_number(input) unless is_a_number? input puts 'Wrong input. Try again and insert a integer next time' return false end input_array = input.to_s.split('') greater_number = input_array.sort.last puts "The greatest input is: #{greater_number}" end def is_a_number?(input) is_a_fixnum = input.is_a? Integer return false unless is_a_fixnum true end greatest_digit_in_number 92_345_678
code/mathematical_algorithms/src/hill_climbing/hill_climbing.java
import java.util.*; public class HillClimbing { public static double findMinimum(BiFunction<Double, Double, Double> f) { double curX = 0; double curY = 0; double curF = f.apply(curX, curY); for (double step = 1e6; step > 1e-7; ) { double bestF = curF; double bestX = curX; double bestY = curY; boolean find = false; for (int i = 0; i < 6; i++) { double a = 2 * Math.PI * i / 6; double nextX = curX + step * Math.cos(a); double nextY = curY + step * Math.sin(a); double nextF = f.apply(nextX, nextY); if (bestF > nextF) { bestF = nextF; bestX = nextX; bestY = nextY; find = true; } } if (!find) { step /= 2; } else { curX = bestX; curY = bestY; curF = bestF; } } System.out.println(curX + " " + curY); return curF; } public static void main(String[] args) { System.out.println(findMinimum((x, y) -> (x - 2) * (x - 2) + (y - 3) * (y - 3))); } }
code/mathematical_algorithms/src/hill_climbing/hill_climbing.py
import math def hill_climbing(function, start, max_iterations, neighbor_function): best_eval = -math.inf current = start best = None for _i in range(max_iterations): if function(current) > best_eval: best_eval = function(current) best = current neighbors = neighbor_function(current) temp_max_eval = -math.inf for neighbor in neighbors: if function(neighbor) > temp_max_eval: current = neighbor temp_max_eval = function(neighbor) return best def neighbor(value): return [value + 1, value - 1] if __name__ == "__main__": function = lambda x: -(x-2)**2 best = hill_climbing(function, 10, 100, neighbor) print(best)
code/mathematical_algorithms/src/horner_polynomial_evaluation/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/horner_polynomial_evaluation/horner_polynomial_evaluation.cpp
#include <iostream> #include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation typedef long long ll; typedef vector<ll> Poly; // evaluate p(x) in linear time ll evaluate(const Poly& p, ll x) { ll ret = 0; for (int i = p.size() - 1; i >= 0; --i) ret = ret * x + p[i]; return ret; } int main() { // polynomial degree int n; scanf("%d", &n); Poly poly(n + 1); // reads coefficients from lowest to highest power for (int i = 0; i <= n; ++i) scanf("%lld", &poly[i]); // number of queries and x to evaluate int q, x; scanf("%d", &q); while (q--) { scanf("%d", &x); printf("%lld\n", evaluate(poly, x)); } return 0; }
code/mathematical_algorithms/src/horner_polynomial_evaluation/horner_polynomial_evaluation.java
import java.io.*; class Horner { // Function that returns value of poly[0]x(n-1) + // poly[1]x(n-2) + .. + poly[n-1] static int horner(int poly[], int n, int x) { // Initialize result int result = poly[0]; // Evaluate value of polynomial using Horner's method for (int i=1; i<n; i++) result = result*x + poly[i]; return result; } // Driver program public static void main (String[] args) { // Let us evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3 int[] poly = {2, -6, 2, -1}; int x = 3; int n = poly.length; System.out.println("Value of polynomial is " + horner(poly,n,x)); } }
code/mathematical_algorithms/src/integer_conversion/decimal_to_any_base.js
// Convert numbers higher than 9 (up to 15) to letters. // Part of Cosmos by OpenGenus Foundation function hex_val(value) { switch (value) { case 10: return "a"; case 11: return "b"; case 12: return "c"; case 13: return "d"; case 14: return "e"; case 15: return "f"; default: return value; } } // Convert a decimal number to any base, from 2 to 16. function decimal_to_base(N, base) { if (base < 2 || base > 16) { throw new Error("Not implemented!"); } var s = ""; while (N > 0) { var val = N % base; s = hex_val(val) + s; N = Math.floor(N / base); } return s; } // Conversion from decimal to hexadecimal. function decimal_to_hexadecimal(N) { return decimal_to_base(N, 16); } // Conversion from decimal to octal. function decimal_to_octal(N) { return decimal_to_base(N, 8); } // Conversion from decimal to binary. function decimal_to_binary(N) { return decimal_to_base(N, 2); }
code/mathematical_algorithms/src/integer_conversion/decimal_to_any_base.py
# property of cosmos decimal_number = float(input("Input the decimal number")) hexadecimal = hex(decimal_number) binary = bin(decimal_number) octodecimal = oct(decimal_number) print("Your input:", decimal_number) print("\n Your number in hexadecimal is:", hexadecimal) print("\n Your number in Binary is:", binary) print("\n Your number in octodecimal is:", octodecimal)
code/mathematical_algorithms/src/integer_conversion/decimal_to_any_base.rs
// Part of Cosmos by OpenGenus Foundation use std::{io::{self, Write}, process}; fn main() { // Print prompt print!("Enter an integer: "); io::stdout().flush().unwrap(); // Read the input string and trim it (remove unnecessary spaces and newline // character) let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let input = input.trim(); // Convert input string to a 64-bit integer. Print an error if it fails and // exit the program. let input = input.parse::<i64>().unwrap_or_else(|_| { println!("Error: Unable to convert input to decimal"); process::exit(1); }); // Store strings that contain the formatted/converted value let decimal = format!("{}", input); let binary = format!("{:b}", input); let hexadecimal = format!("{:X}", input); let octal = format!("{:o}", input); // Print println!("{:>11}: {}", "Hexadecimal", hexadecimal); println!("{:>11}: {}", "Decimal", decimal); println!("{:>11}: {}", "Octal", octal); println!("{:>11}: {}", "Binary", binary); }
code/mathematical_algorithms/src/integer_conversion/decimal_to_bin.cpp
#include <iostream> using namespace std; int main() { int decimal; cout << "Enter a decimal: "; cin >> decimal; cout << "The number in binary: "; for (int i = 31; i >= 0; i--) cout << ((decimal >> i) & 1); cout << endl; return 0; }
code/mathematical_algorithms/src/integer_conversion/decimal_to_hex.cpp
#include <iostream> #include <sstream> #include <string> using namespace std; int main() { int decimal; cout << "Enter a decimal: "; cin >> decimal; stringstream hex; cout << "The number in hexadecimal: "; for (int i = 28; i >= 0; i -= 4) { int val = (decimal >> i) & 0xf; if (val > 9) hex << (char)('a' + (val - 10)); else hex << val; } cout << hex.str() << endl; return 0; }
code/mathematical_algorithms/src/integer_conversion/decimal_to_int.go
//Part of cosmos project from OpenGenus Foundation //Decimal to binay conversion on golang //Written by Guilherme Lucas (guilhermeslcs) package main import ( "strconv" "fmt" ) func to_bin(decimal int) string { var a string; a = "" for decimal > 0 { bit := decimal%2 decimal = decimal/2 //Itoa just converts int to char a = a + strconv.Itoa(bit) } return a } func main() { fmt.Println("Conversion of 5 is", to_bin(5)) fmt.Println("Conversion of 1 is", to_bin(1)) fmt.Println("Conversion of 2 is", to_bin(2)) }
code/mathematical_algorithms/src/integer_conversion/decimal_to_oct.cpp
#include <iostream> #include <sstream> #include <string> using namespace std; int main() { int decimal; cout << "Enter a decimal: "; cin >> decimal; stringstream oct; cout << "The number in octal: "; // This fixes the grouping issue for the first set, which // only contains two bits. oct << (((decimal >> 30) & ~(1 << 2)) & 07); for (int i = 27; i >= 0; i -= 3) oct << ((decimal >> i) & 07); cout << oct.str() << endl; return 0; }
code/mathematical_algorithms/src/integer_to_roman/integer_to_roman.cpp
#include <iostream> #include <string> #include <map> std::string integerToRoman(int number); int main() { int number; std::cout << "Enter a number: "; std::cin >> number; std::cout << "\nYour number: " << number << "\n"; std::cout << "Your number in Roman Numerals: " << integerToRoman(number) << "\n"; } std::string integerToRoman(int number) { static std::map<int, std::string> romanNumerals { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, { 90, "XC"}, { 50, "L"}, { 40, "XL"}, { 10, "X"}, { 9, "IX"}, { 5, "V"}, { 4, "IV"}, { 1, "I"} }; std::string result; for (auto it = romanNumerals.rbegin(); it != romanNumerals.rend(); ++it) while (number >= it->first) { result += it->second; number -= it->first; } return result; }
code/mathematical_algorithms/src/integer_to_roman/integer_to_roman.js
function toRoman(A) { var M = ["", "M", "MM", "MMM"]; let C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; let X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]; let I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; return ( M[Math.floor(A / 1000)] + C[Math.floor((A % 1000) / 100)] + X[Math.floor((A % 100) / 10)] + I[A % 10] ); } console.log(toRoman(3999));
code/mathematical_algorithms/src/integer_to_roman/integer_to_roman.py
romanNumerals = { 1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I", } def integerToRoman(number): result = "" for integer, romanNumber in romanNumerals.items(): while number >= integer: result += romanNumber number -= integer return result num = int(input("Enter a number: ")) print("\nYour number: " + str(num)) print("Your number in Roman Numerals: " + integerToRoman(num))
code/mathematical_algorithms/src/jacobi_method/README.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter # Jacobi method Collaborative effort by [OpenGenus](https://github.com/opengenus) More information in this: [Jacobi method](https://en.wikipedia.org/wiki/Jacobi_method)
code/mathematical_algorithms/src/jacobi_method/jacobi_method.java
/* Part of Cosmos by OpenGenus Foundation */ import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; public class JacobiMethod { private static double e = 0.01; private static void methodJacobi(double[][] matrix, int rows, int cols) { double lastCommonSum = 0; //Sum initial approximation Double[] initAp = new Double[rows]; //Get Initial Approximation for (int i = 0; i < (cols - 1); i++) { double divider = matrix[i][i]; double temp = matrix[i][cols - 1] / divider; temp = new BigDecimal(temp).setScale(2, RoundingMode.HALF_UP).doubleValue(); lastCommonSum = lastCommonSum + temp; initAp[i] = temp; } Double[] tempMassive = new Double[rows]; System.out.println("Start Jacobi method's"); double[][] tempMatrix = new double[rows][cols]; double compare = 1; int f = 0; while (Math.abs(compare) > e) { double commonSum = 0; //Sum next approximation copyMatrix(tempMatrix, matrix); for (int i = 0; i < (cols - 1); i++) { double sum = 0, lastN = 0; for (int ip = 0; ip < (cols); ip++) { if (ip == i) { lastN = tempMatrix[i][ip]; sum = sum + tempMatrix[i][cols - 1]; } else if (ip != cols - 1) { double temp = tempMatrix[i][ip] * initAp[ip] * -1; tempMatrix[i][ip] = new BigDecimal(temp).setScale(6, RoundingMode.HALF_UP).doubleValue(); sum = sum + temp; } else { sum = sum / lastN; } } sum = new BigDecimal(sum).setScale(6, RoundingMode.HALF_UP).doubleValue(); commonSum = commonSum + sum; tempMassive[i] = sum; //massive new values apprx } System.out.println("For f:" + f + " = " + Arrays.toString(tempMassive) + " Last sum: " + lastCommonSum + " next sum: " + commonSum); f++; compare = commonSum - lastCommonSum; //Difference last and next values initAp = tempMassive; lastCommonSum = commonSum; } } private static void printArray(double[][] arr, int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); } private static void copyMatrix(double[][] a, double[][] b) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { a[i][j] = b[i][j]; } } } public static void main(String[] args) { double[][] myMatrix = { {20.9, 1.2, 2.1, 0.9, 21.70}, {1.2, 21.2, 1.5, 2.5, 27.46}, {2.1, 1.5, 19.8, 1.3, 28.76}, {0.9, 2.5, 1.3, 32.1, 49.72}}; System.out.println("Original matrix: "); printArray(myMatrix, 4, 5); methodJacobi(myMatrix, 4, 5); } }
code/mathematical_algorithms/src/karatsuba_multiplication/karatsuba_multiplication.cpp
#include <iostream> // To pad both input strings with 0's so they have same size int equalLength(std::string &bitStr1, std::string &bitStr2) { int strLen1 = bitStr1.size(); int strLen2 = bitStr2.size(); if (strLen1 > strLen2) { int numZerosToPad = strLen1 - strLen2; for (int i = 0; i < numZerosToPad; i++) bitStr2 = '0' + bitStr2; } else if (strLen2 > strLen1) { int numZerosToPad = strLen2 - strLen1; for (int i = 0; i < numZerosToPad; i++) bitStr1 = '0' + bitStr1; } return std::max(strLen1, strLen2); } std::string addBitStrings(std::string bitStr1, std::string bitStr2) { std::string result = ""; int len = equalLength(bitStr1, bitStr2); //For first bit addition carry is 0 int carry = 0; for (int i = len - 1; i >= 0; --i) { // We need to convert '0' or '1' to 0 or 1. Subtracting '0' from the character, subtracts // their ascii values which results in 0 or 1. int bit1 = bitStr1[i] - '0'; int bit2 = bitStr2[i] - '0'; // XOR to add the bits and the previous carry // Adding '0' so that 0 or 1 can be cast to '0' or '1' char sum = (char)((bit1 ^ bit2 ^ carry) + '0'); result = sum + result; // Boolean expression for carry(full adder carry expression) carry = (bit1 & bit2) | (bit2 & carry) | (bit1 & carry); } // if overflow, then add a leading 1 if (carry) result = '1' + result; return result; } long long int karatsubaMultiply(std::string x, std::string y) { int n = equalLength(x, y); //Recursion base cases(when length of the bit string is 0 or 1) if (n == 0) return 0; if (n == 1) // Single bit multiplication. return (x[0] - '0') * (y[0] - '0'); int firstHalfLen = n / 2; int secondHalfLen = (n - firstHalfLen); std::string Xleft = x.substr(0, firstHalfLen); std::string Xright = x.substr(firstHalfLen, secondHalfLen); std::string Yleft = y.substr(0, firstHalfLen); std::string Yright = y.substr(firstHalfLen, secondHalfLen); long long int product1 = karatsubaMultiply(Xleft, Yleft); long long int product2 = karatsubaMultiply(Xright, Yright); long long int product3 = karatsubaMultiply(addBitStrings(Xleft, Xright), addBitStrings(Yleft, Yright)); return product1 * (1 << (2 * secondHalfLen)) + (product3 - product1 - product2) * (1 << secondHalfLen) + product2; } int main() { std::cout << "Product of 1011 and 110 = " << karatsubaMultiply("1011", "110") << "\n"; std::cout << "Product of 1111 and 0 = " << karatsubaMultiply("1111", "0") << "\n"; std::cout << "Product of 100000 and 10 = " << karatsubaMultiply("100000", "10") << "\n"; std::cout << "Product of 101 and 101101 = " << karatsubaMultiply("101", "101101") << "\n"; }
code/mathematical_algorithms/src/karatsuba_multiplication/karatsuba_multiplication.java
import java.util.*; public class KaratsubaMultiply { public static int[] karatsubaMultiply(int[] a, int[] b) { if (a.length < b.length) a = Arrays.copyOf(a, b.length); if (a.length > b.length) b = Arrays.copyOf(b, a.length); int n = a.length; int[] res = new int[n + n]; if (n <= 10) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) res[i + j] = res[i + j] + a[i] * b[j]; } else { int k = n >> 1; int[] a1 = Arrays.copyOfRange(a, 0, k); int[] a2 = Arrays.copyOfRange(a, k, n); int[] b1 = Arrays.copyOfRange(b, 0, k); int[] b2 = Arrays.copyOfRange(b, k, n); int[] a1b1 = karatsubaMultiply(a1, b1); int[] a2b2 = karatsubaMultiply(a2, b2); for (int i = 0; i < k; i++) a2[i] = a2[i] + a1[i]; for (int i = 0; i < k; i++) b2[i] = b2[i] + b1[i]; int[] r = karatsubaMultiply(a2, b2); for (int i = 0; i < a1b1.length; i++) r[i] = r[i] - a1b1[i]; for (int i = 0; i < a2b2.length; i++) r[i] = r[i] - a2b2[i]; System.arraycopy(r, 0, res, k, r.length); for (int i = 0; i < a1b1.length; i++) res[i] = res[i] + a1b1[i]; for (int i = 0; i < a2b2.length; i++) res[i + n] = res[i + n] + a2b2[i]; } return res; } // Usage example public static void main(String[] args) { // (3*x^2+2*x+1) * (4*x+3) = 12*x^3 + 17*x^2 + 10*x + 3 System.out.println(Arrays.equals(new int[]{3, 10, 17, 12, 0, 0}, karatsubaMultiply(new int[]{1, 2, 3}, new int[]{3, 4}))); } }
code/mathematical_algorithms/src/largrange_polynomial/README.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus) # Lagrange Polynomial More information in this: [Lagrange Polynomial](https://en.wikipedia.org/wiki/Lagrange_polynomial) Set in x = 1.5, 2.5, 3.5, and in result we must get a cube of these values. This method is an analogue of Newton's polynomial. The output values are equal. [Newton Polynomial is here](https://github.com/OpenGenus/cosmos/tree/master/code/mathematical-algorithms/newton_polynomial)
code/mathematical_algorithms/src/largrange_polynomial/lagrange_polynomial.java
// Part of Cosmos by OpenGenus Foundation import java.math.BigDecimal; import java.util.ArrayList; public class LagrangePolynomial { private static ArrayList<Double> middleFun = new ArrayList<>(); public static void main(String[] args) { Double[] commonX = {1.0, 2.0, 3.0, 4.0}; Double[] commonFun = {1.0, 8.0, 27.0, 64.0}; Double[] middleX = {1.5, 2.5, 3.5}; basicLagrangePolynomial(commonFun, commonX, middleX); System.out.println(middleFun); } private static void basicLagrangePolynomial(Double[] commonFunValues, Double[] commonPoints, Double[] middlePoints) { for (int importantX = 0; importantX <= middlePoints.length - 1; importantX++) { double number = middlePoints[importantX]; double example; //Counters, so that x does not match when subtracting the numerators. int countA = 0; int countB = 0; double comp3 = 0; for (int q = 0; q <= commonFunValues.length - 1; q++) { double comp = 1; double comp2 = 1; double function = commonFunValues[q]; for (int a = 0; a <= commonPoints.length - 1; a++) { example = commonPoints[a]; if (countA != a) { comp = comp * (number - example); } else { for (int b = 0; b <= commonPoints.length - 1; b++) { double nextN = commonPoints[b]; if (countB != b) { comp2 = comp2 * (example - nextN); } } } } comp3 = comp3 + function * (comp / comp2); countA++; countB++; } //Rounding off values for perfect view BigDecimal test = new BigDecimal(comp3); String round = test.setScale(3, BigDecimal.ROUND_HALF_EVEN).toString(); double comp3Out; comp3Out = Double.parseDouble(round); middleFun.add(comp3Out); } } }
code/mathematical_algorithms/src/lexicographic_string_rank/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/lexicographic_string_rank/lexicographic_string_rank.c
//Part of Cosmos by OpenGenus Foundation #include <stdio.h> #include <string.h> // A utility function to find factorial of n int fact(int n) { return (n <= 1)? 1 :n * fact(n-1); } // A utility function to count smaller characters on right // of arr[low] int findSmallerInRight(char* str, int low, int high) { int countRight = 0, i; for (i = low+1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight; } // A function to find rank of a string in all permutations // of characters int findRank (char* str) { int len = strlen(str); int mul = fact(len); int rank = 1; int countRight; int i; for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // fron str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len-1); rank += countRight * mul ; } return rank; } // Driver program to test above function int main() { char str[] = "string"; printf ("%d", findRank(str)); return 0; }
code/mathematical_algorithms/src/lexicographic_string_rank/lexicographic_string_rank.cpp
/* Part of Cosmos by OpenGenus Foundation */ /* Lexicographic String Rank */ /* O(n) time algorithm */ #include <iostream> #include <string.h> using namespace std; typedef long long ll; void factorial(ll fact[], int n) { fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i; } void initialize_char_cnt(int char_count[], string s, int len) { for (int i = 0; i < 256; i++) char_count[i] = 0; for (int i = 0; i < len; i++) char_count[s[i] - char(0)]++; } void initialize_smaller_char_cnt(int smaller_char_count[], int char_count[]) { smaller_char_count[0] = 0; for (int i = 1; i < 256; i++) smaller_char_count[i] = smaller_char_count[i - 1] + char_count[i - 1]; } void update_char_count(int char_count[], char c) { --char_count[c - char(0)]; } void update_smaller_char_count(int smaller_char_count[], char c) { for (int i = c + 1; i < 256; i++) smaller_char_count[i]--; } ll lexicographic_string_rank(string s) { int len = s.length(); int char_count[256], smaller_char_count[256]; ll fact[len + 1], rep_count = 1, lex_string_rank = 0; factorial(fact, len); //////////// Pre-computation of Factorial is needed for avoiding computing them in future again and again initialize_char_cnt(char_count, s, len); //////////// Initialize char_count array initialize_smaller_char_cnt(smaller_char_count, char_count); //////////// Initialize smaller_char_count array for (int i = 0; i < 256; i++) rep_count *= fact[char_count[i]]; //////////// Repetitive characters will cause duplicate permutations hence rank is divided by rep_count! for (int i = 0; i < len; i++) { lex_string_rank += (fact[len - i - 1] * (smaller_char_count[s[i] - char(0)]) / rep_count); rep_count = rep_count / char_count[s[i] - char(0)]; update_char_count(char_count, s[i]); //////////// Current character no longer needed as its position is fixed now update_smaller_char_count(smaller_char_count, s[i]); } return lex_string_rank; } int main() { string s = "software"; cin >> s; ll lex_string_rank = lexicographic_string_rank(s); cout << "Lexicographic String Rank is: " << lex_string_rank << endl; return 0; }
code/mathematical_algorithms/src/lexicographic_string_rank/lexicographic_string_rank.java
/* * Given a string, find the rank of the string amongst its permutations sorted lexicographically. Assuming that no characters are repeated. */ import java.util.*; public class Rank { public static int findRank(String A) { int length = A.length(); long strFactorial = factorial(length); long rank = 1; for(int i = 0; i < length; i++){ strFactorial /= length - i; rank += findSmallerInRight(A, i, length - 1) * strFactorial; } System.out.println("Rank : "+ Integer.MAX_VALUE); rank %= 1000000007; return (int)rank; } public static long factorial(int n){ return n <= 1? 1: (n * factorial(n - 1)); } public static int findSmallerInRight(String A, int low, int high){ int countRight = 0; for(int i = low + 1; i <= high; i++){ if(A.charAt(i) < A.charAt(low)) countRight++; } return countRight; } // contains count of smaller characters in whole string public static void populateAndIncreaseCount (int[] count, char[] str) { int i; for( i = 0; str[i] >= 'a' && str[i] <= 'z' ; ++i ) ++count[ str[i] ]; for( i = 1; i < 256; ++i ) count[i] += count[i-1]; } // Removes a character ch from count[] array // constructed by populateAndIncreaseCount() public static void updatecount (int[] count, char ch) { int i; for( i = ch; i < 256; ++i ) --count[i]; } // A function to find rank of a string in all permutations // of characters public static int findRank (char[] str) { int len = str.length; long mul = factorial(len); int rank = 1, i; int[] count = new int[256]; // all elements of count[] are initialized with 0 // Populate the count array such that count[i] contains count of // characters which are present in str and are smaller than i populateAndIncreaseCount( count, str ); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // fron str[i+1] to str[len-1] rank += count[ str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount (count, str[i]); } return rank; } public static void main(String[] args) { String A = "aab"; System.out.println(findRank(A.toCharArray())); } }
code/mathematical_algorithms/src/lexicographic_string_rank/lexicographic_string_rank.py
# Part of Cosmos by OpenGenus Foundation def fact(n): f = 1 while n >= 1: f = f * n n = n - 1 return f def findSmallerInRight(st, low, high): countRight = 0 i = low + 1 while i <= high: if st[i] < st[low]: countRight = countRight + 1 i = i + 1 return countRight def findRank(st): ln = len(st) mul = fact(ln) rank = 1 i = 0 while i < ln: mul = mul / (ln - i) countRight = findSmallerInRight(st, i, ln - 1) rank = rank + countRight * mul i = i + 1 return rank
code/mathematical_algorithms/src/log_of_factorial/log_of_factorial.c
/* Part of Cosmos by OpenGenus Foundation */ #include <math.h> #include <stdio.h> double log_factorial(int n){ double ans = 0; for(int i = 1; i <= n; i++) ans += log(i); return ans; } int main(){ int n; scanf("%d",&n); printf("%f",log_factorial(n)); return 0; }
code/mathematical_algorithms/src/log_of_factorial/log_of_factorial.cpp
#include <iostream> #include <cmath> using namespace std; double log_factorial(int n) { double ans = 0; for (int i = 1; i <= n; i++) ans += log(i); return ans; } int main() { int n; cin >> n; cout << log_factorial(n) << endl; return 0; }
code/mathematical_algorithms/src/log_of_factorial/log_of_factorial.java
import java.io.InputStreamReader; import java.util.Scanner; class LogOfFactorial { public static double logOfFactorial(int num) { double ans = 0; for(int i = 1; i <= num; ++i) ans += Math.log(i); return ans; } public static void main(String []args) { Scanner in = new Scanner(new InputStreamReader(System.in)); System.out.println("Enter a number: "); int num = in.nextInt(); System.out.println("Log of Factorial of " + num + " is " + logOfFactorial(num)); in.close(); } }
code/mathematical_algorithms/src/log_of_factorial/log_of_factorial.py
from math import * def log_factorial(n): i = 1 x = 0 while i <= n: x += log10(i) i += 1 return x print("This program will find the log of factorial of entered number.") number_input = int(input("enter your number")) print("log of factorial of", number_input, "is", float(log_factorial(number_input)))
code/mathematical_algorithms/src/lorenz_attractor/Lorenz Attractor.py
import numpy as np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D WIDTH, HEIGHT, DPI = 1000, 750, 100 # Lorenz paramters and initial conditions. sigma, beta, rho = 10, 2.667, 28 u0, v0, w0 = 0, 1, 1.05 # Maximum time point and total number of time points. tmax, n = 100, 10000 def lorenz(t, X, sigma, beta, rho): """The Lorenz equations.""" u, v, w = X up = -sigma*(u - v) vp = rho*u - v - u*w wp = -beta*w + u*v return up, vp, wp # Integrate the Lorenz equations. soln = solve_ivp(lorenz, (0, tmax), (u0, v0, w0), args=(sigma, beta, rho), dense_output=True) # Interpolate solution onto the time grid, t. t = np.linspace(0, tmax, n) x, y, z = soln.sol(t) # Plot the Lorenz attractor using a Matplotlib 3D projection. fig = plt.figure(facecolor='k', figsize=(WIDTH/DPI, HEIGHT/DPI)) ax = fig.gca(projection='3d') ax.set_facecolor('k') fig.subplots_adjust(left=0, right=1, bottom=0, top=1) # Make the line multi-coloured by plotting it in segments of length s which # change in colour across the whole time series. s = 10 cmap = plt.cm.winter for i in range(0,n-s,s): ax.plot(x[i:i+s+1], y[i:i+s+1], z[i:i+s+1], color=cmap(i/n), alpha=0.4) # Remove all the axis clutter, leaving just the curve. ax.set_axis_off() plt.savefig('lorenz.png', dpi=DPI) plt.show()
code/mathematical_algorithms/src/lorenz_attractor/lorenz_attractor.py
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D prandtl = 10 rho = 28 beta = 8 / 3 def lorenz_attr(x, y, z): x_dot = prandtl * (y - x) y_dot = rho * x - y - x * z z_dot = x * y - beta * z return x_dot, y_dot, z_dot dt = 0.01 num_steps = 10000 xs = np.empty(num_steps + 1) ys = np.empty(num_steps + 1) zs = np.empty(num_steps + 1) xs[0], ys[0], zs[0] = (0.0, 1.0, 1.05) for i in range(num_steps): x_dot, y_dot, z_dot = lorenz_attr(xs[i], ys[i], zs[i]) xs[i + 1] = xs[i] + (x_dot * dt) ys[i + 1] = ys[i] + (y_dot * dt) zs[i + 1] = zs[i] + (z_dot * dt) fig = plt.figure() plt.style.context("dark_background") ax = fig.gca(projection="3d") ax.plot(xs, ys, zs, lw=0.5) ax.set_xlabel("X-Axis") ax.set_ylabel("Y-Axis") ax.set_zlabel("Z-Axis") ax.set_title("Lorenz Attractor") plt.style.use("dark_background") plt.show()
code/mathematical_algorithms/src/lucas_theorem/lucas_theorem.cpp
// A Lucas Theorem based solution to compute nCr % p #include <iostream> #include <cmath> // Returns nCr % p. In this Lucas Theorem based program, // this function is only called for n < p and r < p. int nCrModpDP(int n, int r, int p) { // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int C[r + 1]; for (size_t i = 0; i < sizeof(C); ++i) C[i] = 0; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) // Fill entries of current row using previous // row values for (int j = std::min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; return C[r]; } // Lucas Theorem based function that returns nCr % p // This function works like decimal to binary conversion // recursive function. First we compute last digits of // n and r in base p, then recur for remaining digits int nCrModpLucas(int n, int r, int p) { // Base case if (r == 0) return 1; // Compute last digits of n and r in base p int ni = n % p, ri = r % p; // Compute result for last digits computed above, and // for remaining digits. Multiply the two results and // compute the result of multiplication in modulo p. return (nCrModpLucas(n / p, r / p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits } // Driver program int main() { using namespace std; int n = 1000, r = 900, p = 13; cout << "Value of nCr % p is " << nCrModpLucas(n, r, p); return 0; }
code/mathematical_algorithms/src/lucky_number/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/lucky_number/lucky_number.c
/* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> #define bool int bool isLucky(int n) { static int counter = 2; int next_position = n; if (counter > n) return (1); if (n % counter == 0) return (0); next_position -= next_position/counter; counter++; return isLucky(next_position); } int main() { int x = 5; if (isLucky(x)) printf("%d is a lucky no.", x); else printf("%d is not a lucky no.", x); }
code/mathematical_algorithms/src/lucky_number/lucky_number.java
import java.io.*; // Part of Cosmos by OpenGenus Foundation class Main { static int counter = 2; static boolean isLucky(int n) { int next_position = n; if(counter > n) { return true; } if(n % counter == 0) { return false; } next_position -= next_position/counter; counter++; return isLucky(next_position); } public static void main(String args[]) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a number"); int x = Integer.parseInt(stdin.readLine()); if( isLucky(x) ) { System.out.println(x + " is a lucky no."); } else { System.out.println(x + " is not a lucky no."); } } }
code/mathematical_algorithms/src/magic_square/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/magic_square/magic_square.py
# Python program to generate odd sized magic squares # A function to generate odd sized magic squares def generateSquare(n): # 2-D array with all slots set to 0 magicSquare = [[0 for x in range(n)] for y in range(n)] # initialize position of 1 i = n / 2 j = n - 1 # Fill the magic square by placing values num = 1 while num <= (n * n): if i == -1 and j == n: # third condition j = n - 2 i = 0 else: # next number goes out of right side of square if j == n: j = 0 # next number goes out of upper side if i < 0: i = n - 1 if magicSquare[i][j]: # 2nd condition j = j - 2 i = i + 1 continue else: magicSquare[i][j] = num num = num + 1 j = j + 1 i = i - 1 # 1st condition # Printing magic square print("Magic Squre for n = ", n) print("Sum of each row or column", n * (n * n + 1) / 2) for i in range(0, n): for j in range(0, n): print("%2d " % (magicSquare[i][j]), end=" ") print() # Driver program # Works only when n is odd n = 7 generateSquare(n)
code/mathematical_algorithms/src/matrix_row_reduction/matrix_row_reduction.cpp
#include<iostream> #include<string> #include<vector> #include<set> using namespace std; void PrintMatrix(vector<vector<float>>& matrix); //Prints matrix to console int FirstNonZero(vector<float>& vec); //find first non-zero coefficient in a given row, returns -1 if unfound void RowReduction(vector<vector<float>>& matrix) { //Reduces a matrix to it's reduced row echelon form int iteration = 0; while (iteration != matrix[0].size() - 1) { for (int i = iteration; i < matrix.size(); i++) { float divisor = 1; int pivot = FirstNonZero(matrix[i]); if (pivot != -1) divisor = matrix.at(i).at(pivot); for (int j = 0; j < matrix[i].size(); j++) if (pivot != -1) matrix[i][j] /= divisor; } for (int i = iteration + 1; i < matrix.size(); i++) { int pivot = FirstNonZero(matrix[iteration]); if (pivot != -1 && matrix[i][pivot] != 0) { for (int j = pivot; j < matrix.at(i).size(); j++) { matrix[i][j] -= matrix[iteration][j]; } } } iteration++; } //correct the row order for (int i = 0; i < matrix.size(); i++) { int index = FirstNonZero(matrix.at(i)); if (index == -1) { continue; } vector<float> temp = matrix[index]; matrix[index] = matrix.at(i); matrix[i] = temp; } cout << "Row Echelon Form:" << endl; PrintMatrix(matrix); cout << endl; //test if system is consistent set<int> pivots; for (vector<float> row : matrix) { if (FirstNonZero(row) == -1) { if (row.back() != 0) { cout << "The System of Equations has No Solution" << endl; return; } } else pivots.insert(FirstNonZero(row)); } unsigned int freeVar = matrix[0].size() - 1 - pivots.size(); if (freeVar == 0) cout << "The System of Equations has one Solution" << endl; else cout << "The System of Equations has many Solutions" << endl; cout << "The System has " << freeVar << " free variable(s).\n" << endl; iteration = matrix.size() - 1; //Reduces the matrix to its reduced echelon form while (iteration > 0) { for (int i = 0; i < iteration; i++) { int pivot = FirstNonZero(matrix[iteration]); float multiple = 0; if (pivot != -1) multiple = matrix.at(i).at(pivot); for (int j = 0; j < matrix.at(i).size(); j++) { matrix[i][j] -= (matrix[iteration][j] * multiple); } } iteration--; } cout << "Reduced Echelon From:" << endl; PrintMatrix(matrix); if (freeVar == 0) { //Case 1 there is a single solution vector<float> solutions; solutions.resize(matrix[0].size() - 1); for (vector<float> row : matrix) { if (FirstNonZero(row) == -1) continue; float val = round(row.back() * 100.0) / 100.0; if (val == -0) val = 0; solutions.at(FirstNonZero(row)) = val; } cout << "\nThe solution to this set of Equations is ("; for (float val : solutions) { if (val == solutions.back()) cout << val << ")\n"; else cout << val << ", "; } } else { //Case 2 there are infinite solutions vector<string> equations; equations.resize(matrix[0].size() - 1); for (vector<float> row : matrix) { int index = FirstNonZero(row); if (index == -1) continue; string equation = ""; for (int i = index + 1; i < row.size(); i++) { float value = round(row[i] * 100.0) / 100.0; if (value != 0 && value != -0) { float absVal = abs(value); string temp = to_string(absVal); if (i == row.size() - 1) { if (equation == "") { if (value < 0) equation.append("-"); } else { if (value > 0) equation.append(" + "); else equation.append(" - "); } equation.append(temp.substr(0, temp.find_first_of('.') + 3)); } else { if (equation == "") { if (value > 0) equation.append("-"); } else { if (value < 0) equation.append(" + "); else equation.append(" - "); } equation.append(temp.substr(0, temp.find_first_of('.') + 3) + "X" + to_string(i + 1)); } } } equations[index] = equation; } cout << "\nThe solution set to this set of Equations is ("; for (int i = 0; i < equations.size(); i++) { if (equations.at(i) == "") equations.at(i) = "X" + to_string(i + 1); if (i == equations.size() - 1) cout << equations.at(i) << ")\n"; else cout << equations.at(i) << ", "; } } } //Prints Matrix void PrintMatrix(vector<vector<float>>& matrix) { for (vector<float> row : matrix) { for (float value : row) { if (value == -0) cout << "0 "; else cout << value << " "; } cout << endl; } } //Find the index of the first non zero value in a row returns -1 if all but the last value are zero int FirstNonZero(vector<float>& vec) { for (int i = 0; i < vec.size() - 1; i++) { if (vec.at(i) != 0 && vec.at(i) != -0) return i; } return -1; } void main() { //This is just the input for the matrix to solve the system of equations, just an example so you can use the algorithm cout << "Please insert the coefficients of each equation separated by semicolons (A;B;C:...:N;b)\nEquations should be in the form Ax + By + Cz + ... + Nn = b. Separate each equation with a new line." << endl << "Type 'solve' when finished" << endl; string input = ""; string delimiter = ";"; size_t pos = 0; vector<vector<float>> matrix; int row = 0; int columnSize = 0; while (1) { int currColumnSize = 0; vector<float> tempVec; getline(cin, input); if (input == "solve") break; while ((pos = input.find(delimiter)) != std::string::npos) { if (input.substr(0, pos).find_first_not_of("0123456789-") != std::string::npos) { cout << "Error: Invalid Coefficient\n\nCoefficient is not an integer" << endl; return; } int temp = stoi(input.substr(0, pos)); tempVec.push_back(temp);; input.erase(0, pos + delimiter.length()); currColumnSize++; } int temp = stoi(input); tempVec.push_back(temp); currColumnSize++; if (currColumnSize != columnSize && columnSize != 0) { cout << "Error: Invalid Formating" << endl << endl << "All Rows do not have the same number of columns.\nIf an equation is missing a variable there should be a coefficient of 0 to fill its place." << endl; return; } columnSize = currColumnSize; matrix.push_back(tempVec); row++; } cout << "\nMatrix you entered:" << endl; PrintMatrix(matrix); cout << endl; //This is where the actual algorithm starts RowReduction(matrix); }
code/mathematical_algorithms/src/maximum_perimeter_triangle/PerimeterTriangle.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class PerimeterTriangle { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); br.readLine(); br.readLine(); //no. of elements in array int n = Integer.parseInt(br.readLine()); int[] sides = new int[n]; String[] input; input = br.readLine().split(" "); for(int i=0; i<n; i++){ sides[i] = Integer.parseInt(input[i]); } Arrays.sort(sides); boolean flag = false; //starting from end, because we have sorted in //ascending order and we want the max element //first, you could also sort in descending order //and start from i=0 for(int i=n-1; i>=2; i--){ if(sides[i-2]+sides[i-1]>sides[i]){ System.out.println(sides[i-2]+" "+sides[i-1]+" "+sides[i]); flag = true; break; } } if(flag==false){ System.out.println("-1"); } } }
code/mathematical_algorithms/src/minimum_operations_elements_equal/EqualizeEveryone.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class EqualizeEveryone { public static void main(String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0){ int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; String[] input = br.readLine().split(" "); int min = Integer.MAX_VALUE; for(int i=0; i<n; i++){ arr[i] = Integer.parseInt(input[i]); min = Math.min(arr[i],min); } int minOperations = 0; for(int i=0; i<n; i++){ minOperations += arr[i]-min; } System.out.println(minOperations); } } }
code/mathematical_algorithms/src/modular_inverse/modular_inverse.cpp
#include <stdio.h> int modularInverse(int number, int mod); void extendedEuclid(int, int, int* d, int* x, int* y); int main() { int number, mod; scanf("%d %d", &number, &mod); int ans = modularInverse(number, mod); if (ans == -1) fprintf(stderr, "Couldn't calculate modular inverse!\n"); else printf("%d", ans); } int modularInverse(int number, int mod) { if (1 <= number && number <= mod - 1) { int x, y, d; extendedEuclid(number, mod, &d, &x, &y); if (d == 1) { while (x < 0) x += mod; return x; } else fprintf(stderr, "The number and mod need to be coprime\n"); } else fprintf(stderr, "Number needs to be between 1 and mod!\n"); return -1; } void extendedEuclid(int a, int b, int* d, int* x, int* y) { if (b == 0) { *x = 1; *y = 0; *d = a; return; } int x0, y0; extendedEuclid(b, a % b, d, &x0, &y0); *x = y0; *y = x0 - (a / b) * y0; }
code/mathematical_algorithms/src/modular_inverse/modular_inverse.java
import java.util.Scanner; // Part of Cosmos by OpenGenus Foundation public class Main { /// Holds 3 long integers static class Trint { final long first, second, third; Trint (long first, long second, long third) { this.first = first; this.second = second; this.third = third; } } // Returns values x, y and d for which a*x + b*y = d, where d is GCD(a, b) private static Trint extendedEuclid(long a, long b) { if (b == 0) { return new Trint(1, 0, a); } /// calculate result for b, a%b Trint result = extendedEuclid(b, a%b); return new Trint(result.second, result.first - (a / b) * result.second, result.third); } // Returns the modular inverse (for which number * inverse % mod == 1) public static long modularInverse(long number, long mod) { if (number < 1 || number >= mod) throw new RuntimeException("Number should lie between 1 and mod (" + mod + ")"); Trint result = extendedEuclid(number, mod); long inverse = result.first, gcd = result.third; if (gcd != 1) throw new RuntimeException(String.format("The number (%d) and mod (%d3) are not coprime", number, mod)); /// Ensure inverse lies between 0 and mod if (inverse < 0) inverse += ((long)Math.ceil(Math.abs((double)inverse) / mod)) * mod; return inverse; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the number: "); long number = input.nextLong(); System.out.println("Enter the modulo: "); long mod = input.nextLong(); long inverse = modularInverse(number, mod); System.out.println("The inverse is " + inverse); if (number * inverse % mod != 1) System.out.println("Something went wrong"); } }
code/mathematical_algorithms/src/modular_inverse/modular_inverse.py
def extendedEuclid(a, b): if b == 0: return (a, 1, 0) (_d, _x, _y) = extendedEuclid(b, a % b) return (_d, _y, _x - (a // b) * (_y)) def modInverse(num, mod): if num < 1 or num >= mod: raise Exception("Number should lie between 1 and mod ({})!".format(str(mod))) else: (d, x, y) = extendedEuclid(num, mod) if d == 1: while x < 0: x += mod return x else: raise Exception( "The number ({0}) and mod ({1}) are not coprime!".format( str(num), str(mod) ) ) return -1 num, mod = list(map(int, input().split())) res = modInverse(num, mod) if res == -1: raise Exception("Modular inverse couldn't be calculated!") else: print(res)
code/mathematical_algorithms/src/modular_inverse/modular_inverse.rb
# Part of Cosmos by OpenGenus Foundation def extended_gcd(a, b) last_remainder = a.abs remainder = b.abs x = 0 last_x = 1 y = 1 last_y = 0 while remainder != 0 (quotient, remainder) = last_remainder.divmod(remainder) last_remainder = remainder x, last_x = last_x - quotient * x, x y, last_y = last_y - quotient * y, y end [last_remainder, last_x * (a < 0 ? -1 : 1)] end def invmod(e, et) g, x = extended_gcd(e, et) raise 'The maths are broken!' if g != 1 x % et end
code/mathematical_algorithms/src/multiply_polynomial/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/multiply_polynomial/multiply_polynomial.cpp
// Templated Implementation of FFT. // Used to multiply 2 polynomials of size N in O(N logN). // Polynomials are passed as vectors with index of "i" is // coefficient of x^i in polynomial. #include <iostream> #include <cmath> #include <vector> const int MAX = 131100; //2^ceil(log2(N)) where N = Maximum size of Polynomial //Complex class: Quite faster than in-built C++ library as it uses // only functions required template<typename T> class cmplx { private: T x, y; public: cmplx () : x(0.0), y(0.0) { } cmplx (T a) : x(a), y(0.0) { } cmplx (T a, T b) : x(a), y(b) { } T get_real() { return this->x; } T get_img() { return this->y; } cmplx conj() { return cmplx(this->x, -(this->y)); } cmplx operator = (const cmplx& a) { this->x = a.x; this->y = a.y; return *this; } cmplx operator + (const cmplx& b) { return cmplx(this->x + b.x, this->y + b.y); } cmplx operator - (const cmplx& b) { return cmplx(this->x - b.x, this->y - b.y); } cmplx operator * (const T& num) { return cmplx(this->x * num, this->y * num); } cmplx operator / (const T& num) { return cmplx(this->x / num, this->y / num); } cmplx operator * (const cmplx& b) { return cmplx(this->x * b.x - this->y * b.y, this->y * b.x + this->x * b.y); } cmplx operator / (const cmplx& b) { cmplx temp(b.x, -b.y); cmplx n = (*this) * temp; return n / (b.x * b.x + b.y * b.y); } }; //T = int/long long as per polynomial coefficients //S = double/long double as per precision required template<typename T, typename S> struct FFT { S PI; int n, L, *rev, last; cmplx<S> ONE, ZERO; cmplx<S> *omega_powers; FFT() { PI = acos(-1.0); ONE = cmplx<S>(1.0, 0.0); ZERO = cmplx<S>(0.0, 0.0); last = -1; int req = 1 << (32 - __builtin_clz(MAX)); rev = new int[req]; omega_powers = new cmplx<S>[req]; } ~FFT() { delete rev; delete omega_powers; } void ReverseBits() { if (n != last) for (int i = 1, j = 0; i < n; ++i) { int bit = n >> 1; for (; j >= bit; bit >>= 1) j -= bit; j += bit; rev[i] = j; } } void DFT(std::vector<cmplx<S>> &A, bool inverse = false) { using namespace std; for (int i = 0; i < n; ++i) if (rev[i] > i) swap(A[i], A[rev[i]]); for (int s = 1; s <= L; s++) { int m = 1 << s, half = m / 2; cmplx<S> wm(cosl(2.0 * PI / m), sinl(2.0 * PI / m)); if (inverse) wm = ONE / wm; omega_powers[0] = ONE; for (int k = 1; k < half; ++k) omega_powers[k] = omega_powers[k - 1] * wm; for (int k = 0; k < n; k += m) for (int j = 0; j < half; j++) { cmplx<S> t = omega_powers[j] * A[k + j + half]; cmplx<S> u = A[k + j]; A[k + j] = u + t; A[k + j + half] = u - t; } } if (inverse) for (int i = 0; i < n; i++) A[i] = A[i] / n; } // c[k] = sum_{i=0}^k a[i] b[k-i] std::vector<T> multiply(const std::vector<T> &a, const std::vector<T> &b) { using namespace std; L = 0; int sa = a.size(), sb = b.size(), sc = sa + sb - 1; while ((1 << L) < sc) L++; n = 1 << L; ReverseBits(); last = n; vector<cmplx<S>> aa(n, ZERO), bb(n, ZERO), cc; for (int i = 0; i < sa; ++i) aa[i] = cmplx<S>(a[i], 0); for (int i = 0; i < sb; ++i) bb[i] = cmplx<S>(b[i], 0); DFT(aa, false); DFT(bb, false); for (int i = 0; i < n; ++i) cc.push_back(aa[i] * bb[i]); DFT(cc, true); vector<T> ans(sc); for (int i = 0; i < sc; ++i) ans[i] = cc[i].get_real() + 0.5; return ans; } }; int main() { using namespace std; vector<int> poly_1(4); //1 + 3x^2 + 2x^3 poly_1[0] = 1; poly_1[1] = 0; poly_1[2] = 3; poly_1[3] = 2; vector<int> poly_2(3); //2 + x + x^2 poly_2[0] = 2; poly_2[1] = 1; poly_2[2] = 1; // int = final datatype in which coefficients should fit. // double = internal calculations done in double but has precision loss. // use "long double" to get less precision issues, but constant factor // of algorithm increases. FFT<int, double> fft; // Product should be 2 + x + 7x^2 + 7x^3 + 5x^4 + 2x^5 std::vector<int> poly_mul = fft.multiply(poly_1, poly_2); for (size_t i = 0; i < poly_mul.size(); ++i) cout << poly_mul[i] << " "; cout << "\n"; return 0; }
code/mathematical_algorithms/src/newman_conway/README.md
# Newman-Conway Sequence The recursive sequence defined by its recurrence relation ## Explaination ### Recurrence Relation `P(1) = 1,` `P(2) = 1,` `P(n) = P (P(n-1) ) + P( n - P(n-1) )` ### Pattern 1, 1, 2, 2, 3, 4, 4, 4, 5, 6, ... ## Complexity To compute n<sup>th</sup> Newman-Conway Number. `Time Complexity: O(n)` `Space Complexity: O(n)` --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/mathematical_algorithms/src/newman_conway/newman_conway_recursion.cpp
#include <iostream> class NewmanConwaySequence { public: NewmanConwaySequence(unsigned int n) : n(n) {} unsigned int calculateNewmanConwaySequenceTermRecur(unsigned int n); private: unsigned int n; }; unsigned int NewmanConwaySequence::calculateNewmanConwaySequenceTermRecur(unsigned int n) { if(n == 1 or n == 2) return 1; else return calculateNewmanConwaySequenceTermRecur(calculateNewmanConwaySequenceTermRecur(n - 1)) + calculateNewmanConwaySequenceTermRecur(n - calculateNewmanConwaySequenceTermRecur(n - 1)); } int main() { unsigned int nValue; std::cout << "\nEnter the Index of Newman Conway Sequence : "; std::cin >> nValue; NewmanConwaySequence aNewmanConwaySequenceObj(nValue); std::cout << "\nValue of term at " << nValue << " indexed in Newman Conway Sequence : " << aNewmanConwaySequenceObj.calculateNewmanConwaySequenceTermRecur(nValue); }
code/mathematical_algorithms/src/newman_conway/newman_conway_sequence.c
#include <stdio.h> void newman_conway_sequence(int number_of_terms) { int array[number_of_terms + 1]; array[0] = 0; array[1] = 1; array[2] = 1; int i; for (i = 3; i <= number_of_terms; i++) array[i] = array[array[i - 1]] + array[i - array[i - 1]]; for (i = 1; i <= number_of_terms; i++) printf("%d ",array[i]); printf("\n"); } int main() { int number_of_terms = 20; newman_conway_sequence(number_of_terms); return (0); }
code/mathematical_algorithms/src/newman_conway/newman_conway_sequence.cpp
#include <iostream> #include <vector> //prints input number of teerms of Newman-Conway Sequence std::vector<int> NewmanConwaySequence(int number) { std::vector<int> arr(number + 1); arr[0] = 0; arr[1] = 1; arr[2] = 1; for (int i = 3; i <= number; ++i) arr[i] = arr[arr[i - 1]] + arr[i - arr[i - 1]]; return arr; } int main() { int number; std::cout << "Enter number: "; std::cin >> number; std::vector<int> sequence(number + 1); sequence = NewmanConwaySequence(number); for (int i = 1; i <= number; ++i) std::cout << sequence[i] << " "; return 0; }
code/mathematical_algorithms/src/newton_polynomial/README.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus) # Newton Polynomial Okay. More information in this: [Newton Polynomial](https://en.wikipedia.org/wiki/Newton_polynomial) We release it with help divided differences. To verify the correct values, we set in x the difference between the first and second. For example: 1 2 3 4 Set in x = 1.5, 2.5, 3.5, and in result we must get a cube of these values. Also, divided difference is here: [Click me](https://github.com/OpenGenus/cosmos/tree/master/code/mathematical-algorithms/divided_differences) However you can implement the divided differences in your own way.
code/mathematical_algorithms/src/newton_polynomial/newton_polynomial.java
public class NewtonPolynomial { private static ArrayList<Double> output = new ArrayList<>(); private static void divided_diff(double[][] matrix, int sLength) { int i = 1, i2 = 2, j = 2, s2 = sLength; for (int z = 0; z < sLength - 1; z++, j++, s2 -= 1, i2++) { for (int y = 0; y < s2 - 1; y++, i += 2) { matrix[i][j] = (matrix[i + 1][j - 1] - matrix[i - 1][j - 1]) / (matrix[i + (i2 - 1)][0] - matrix[i - (i2 - 1)][0]); } i = i2; } } private static void newtonPolynomial(double[][] massive, int sLength) { ArrayList<Double> list = new ArrayList<>(); int h = 1; for (int i = 0; i < (sLength * 2 - 1) / 2 + 1; i++) { for (int j = 1; j < 2; j++) { double g = massive[i][h]; list.add(g); } h++; } for (int i = 0; i < (sLength * 2 - 1); i++) { System.out.println(Arrays.toString(massive[i])); } Double[] listMas = list.toArray(new Double[list.size()]); ArrayList<Double> arrPoints = new ArrayList<>(); System.out.println(); System.out.println(arrPoints); int m = 0; for (int i = 0; i < (sLength * 2 - 1) / 2 + 2; i++) { double q = massive[i][0]; arrPoints.add(q); m++; } for (int g = 0; g < arrPoints.size(); g++) { if (arrPoints.get(g) == 0) { double temp = arrPoints.get(g); arrPoints.remove(g); arrPoints.add(temp); } } Double[] pointsX = arrPoints.toArray(new Double[arrPoints.size()]); for (double x = 1.5; x < 4; x++) { double sum = listMas[0]; double peremen = 0; for (int i = 0; i < listMas.length; i++) { double predsum = 1; int sk = 0; if (sk != i) { for (int j = 0; j < i; j++) { predsum = predsum * (x - pointsX[j]); } peremen = listMas[i] * predsum; } sum = sum + peremen; } output.add(sum); System.out.println(sum); } } public static void main(String[] args) { Double[] commonValues = {1.0, 2.0, 3.0, 4.0}; Double[] commonFunValues = {1.0, 8.0, 27.0, 64.0}; int length = commonValues.length; double[][] mas = new double[(2 * length) - 1][length + 1]; for (int i = 0, z = 0; i < length; i++, z += 2) { mas[z][0] = commonValues[i]; mas[z][1] = commonFunValues[i]; } divided_diff(mas, length); newtonPolynomial(mas, length); System.out.println(output); } }
code/mathematical_algorithms/src/newton_raphson_method/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/newton_raphson_method/newton_raphson.c
/* Part of Cosmos by OpenGenus Foundation */ #include<stdio.h> #include<math.h> float f(float x) {     return x*log10(x) - 1.2; } float df (float x) {     return log10(x) + 0.43429; } int main() {     int itr, maxmitr;     float h, x0, x1, allerr;     printf("\nEnter x0, allowed error and maximum iterations\n");     scanf("%f %f %d", &x0, &allerr, &maxmitr);     for (itr=1; itr<=maxmitr; itr++)     {         h=f(x0)/df(x0);         x1=x0-h;         printf(" At Iteration no. %3d, x = %9.6f\n", itr, x1);         if (fabs(h) < allerr)         {             printf("After %3d iterations, root = %8.6f\n", itr, x1);             return 0;         }         x0=x1;     }     printf(" The required solution does not converge or iterations are insufficient\n");     return 1; }