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];
}
fibonac... |
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(fi... |
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])
... |
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].t... |
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!("{}",fib... |
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
de... |
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-38... |
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 p... |
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
* ... |
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;... |
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 =
... |
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 ) NotSingul... |
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
... |
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.dec... |
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: ... |
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
overr... |
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 mo... |
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");
s... |
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%... |
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)
... |
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... |
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... |
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) f... |
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(... |
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(... |
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));
re... |
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;
... |
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_digi... |
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 = [
... |
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_numbe... |
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_fi... |
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;
boo... |
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 = neighb... |
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 r... |
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 (... |
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:
ret... |
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... |
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();
... |
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;
... |
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 = decima... |
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.
... |
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) <<... |
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[... |
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 ... |
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 ini... |
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 ... |
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 ... |
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.... |
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[] comm... |
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)
{
... |
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 initia... |
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);
... |
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
... |
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.... |
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... |
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 point... |
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.empt... |
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... |
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... |
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;
... |
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 ... |
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>>& mat... |
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();... |
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())... |
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... |
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;
thi... |
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, ... |
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... |
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 o... |
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 Complex... |
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)
{
i... |
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[... |
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... |
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 ... |
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... |
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");
sc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.