filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/mathematical_algorithms/src/sieve_of_eratosthenes/README.md | # Sieve of Eratosthenes
Learn at [**OpenGenus IQ**](https://iq.opengenus.org/the-sieve-of-eratosthenes/)
Sieve of Eratosthenes is used to find prime numbers up to some predefined integer n. For sure, we can just test all the numbers in range from 2 to n for primality using some approach, but it is quite inefficient. ... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.c | #include <stdio.h>
#include <stdlib.h>
/* Part of Cosmos by OpenGenus Foundation */
int sieve_of_eratosthenes(int **primes, const int max) {
// Allocate memory
int *isPrime = (int *)malloc(sizeof(int) * (max + 1));
int i;
// Assume all numbers to be prime initially
for(i = 0; i <= max; ++i)
isPrime[i] = 1;
// 0... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.cpp | #include <iostream>
#include <vector>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
void SieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
vector<boo... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.cs | using System;
using System.Linq;
namespace OpenGenus
{
// Part of Cosmos by OpenGenus Foundation
class Program
{
public static void Main(string[] args)
{
var random = new Random();
var n = random.Next(1, 1000);
var primes = SieveOfEratosthenes(n);
Console.WriteLine($"Primes up to {n}... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.go | package main
import "fmt"
// Part of Cosmos by OpenGenus Foundation
func SieveOfEratosthenes(n int) []int {
//Create an array of Boolean values indexed by
//integers 2 to n, initially all set to true.
integers := make([]bool, n+1)
for i := 2; i < n+1; i++ {
integers[i] = true
}
for i := 2; i*i <= n; i++ {
... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.hs | module Eratosthenes where
-- Part of Cosmos by OpenGenus Foundation
eratosthenes :: [Integer] -- A list of all prime numbers
eratosthenes = go [2..]
where
-- If we have something in the front of the list (x:xs),
-- we know it wasn't filtered, so it's prime.
-- Then, we filter the rest of the list to exc... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.Scanner; //To take the input the scanner class has to be imported.
public class erathosthenes{
public void sieve (int n) {
boolean checkPrime[] = new boolean [n+1]; //checkPrime array to mark the elements whether they are prime or no... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.js | class SieveOfEratosthenes {
/**
* @constructor
* @param {number} max - max number to test up to
* Part of Cosmos by OpenGenus Foundation
*/
constructor(max) {
this._max = max;
this._sqrtMax = Math.ceil(Math.sqrt(this._max));
// Get an array from number 2 up to max. Start from 2 because 0 an... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* Find all prime numbers up to any given n using Sieve of Eratosthenes.
*
* @param int $n
*
* @return array|integer
*/
function sieveOfEratosthenes($n)
{
if ($n <= 1) {
return -1;
}
$array = array_fill_keys(range(2, $n), true);
for ($... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes.py | import sys
# Part of Cosmos by OpenGenus Foundation
def sieve_erato(n):
loops = 0
numbers = set(range(2, n))
for i in range(2, int(n ** 0.5) + 1):
for j in range(i * 2, n, i):
numbers.discard(j)
loops += 1
return sorted(numbers), loops
try:
primes = sieve_erato(int... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes_compact.cpp | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 0;
cin >> n;
++n;
vector<bool> primes(n, true);
primes[0] = false; // as 0 is not a prime
primes[1] = false; // as 1 is not a prime
int k = 2;
for (int i = 2; i < n; ++i)
{
wh... |
code/mathematical_algorithms/src/sieve_of_eratosthenes/sieve_of_eratosthenes_linear.cpp | #include <iostream>
#include <vector>
/* Part of Cosmos by OpenGenus Foundation */
// Time complexity: O(n)
std::vector<int> sieve_linear(int n)
{
std::vector<int> min_divider(n + 1); // min_divider[i] is the minimum prime divider of i
std::vector<int> primes;
for (int i = 2; i <= n; i++)
{
if... |
code/mathematical_algorithms/src/simpsons_rule/simpsons_rule.cpp | #include <iostream>
#include <cmath>
float create(int x)
{
return log(x);
}
int simpson(int x1, int x2)
{
float h = (x2 - x1) / 6;
int x[10];
float y[10];
for (int i = 0; i <= n; ++i) {
x[i] = x1 + i * h;
y[i] = create(x[i]);
}
float value = 0;
for (int i = 0; i <= n; ... |
code/mathematical_algorithms/src/simpsons_rule/simpsons_rule.py | from math import sqrt
from scipy.integrate import quad
def simpson(f, a, b, n):
def compute_141(x, index):
return 2 * f(x) if index % 2 == 0 else 4 * f(x)
n = n if n % 2 == 0 else 2 * n
h = (b - a) / n
return (h / 3) * (f(a) + f(b) + sum(compute_141(a + i * h, i) for i in range(1, n)))
a, b... |
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.c | #include<stdio.h>
// Part of Cosmos by OpenGenus Foundation
int
smallest_digit(int n)
{
int min_digit = n % 10;
while (n) {
min_digit = (min_digit > n % 10) ? n % 10 : min_digit;
n /= 10;
}
return (min_digit);
}
int
main()
{
int n;
scanf("%d", &n);
printf("smallest digit i... |
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.cpp | #include <iostream>
using namespace std;
int smallest_digit(int n)
{
int min = n % 10; //assume that last digit is the smallest
n /= 10; //to start from the second last digit
while (n != 0)
{
if (min > n % 10)
min = n % 10;
n /= 10;
}
return min;
}
int main()
{
i... |
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.cs | using System;
namespace SmallestNumber
{
public class Program
{
private static int smallestNumber(int n)
{
int min = n % 10;
n /= 10;
while(n != 0)
{
if(n % 10 < min)
{
min = n % 10;... |
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.hs | smallest :: Integer -> Integer
smallest n
| modOfTen == n = n
| otherwise = modOfTen `min` greatest quotOfTen
where modOfTen = mod n 10
quotOfTen = quot n 10
|
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.*;
class smallest_digit_in_number{
public static void main(String args[]) {
int num = 238493;
System.out.println(smallest_digit(num));
}
// returns the smallest integer of a given number.
public static int smallest_digit(int ... |
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.js | const smallest_digit_in_number = input => {
if (typeof input !== "number") {
console.error("Please enter a number.");
return;
}
const numbers = [];
let number = input;
while (number > 0) {
const n = number % 10;
numbers.push(n);
number = Math.floor(number / 10);
}
numbers.sort();... |
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* Finds the smallest digit in number
*
* @param int $num number
* @return int smallest digit
*/
function smallest_digit_in_number(int $num)
{
return min(array_map('intval', str_split($num)));
}
echo "smallest digit in number\n";
$test_data = [
... |
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.py | #!/usr/bin/python3
def smallest_digit(n):
min_digit = int(n % 10)
while n != 0:
if min_digit > n % 10:
min_digit = n % 10
n //= 10
print(int(min_digit))
return min_digit
user_number = int(input("enter number: "))
print("smallest digit is :\n", int(smallest_digit(use... |
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.rb | # Part of Cosmos by OpenGenus Foundation
def smallest_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('')
smaller_number = input_array.sort.first
puts "The smallest input is: #{smaller_numbe... |
code/mathematical_algorithms/src/spiral_matrix/recursive_spiral_matrix.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
using namespace std;
/*
This algorithm takes in a 2-dimensional vector and
outputs its contents in a clockwise spiral form.
Example Input:
[ [ 1 2 3 4 ],
[ 5 6 7 8 ],
[ 9 10 11 12 ],
... |
code/mathematical_algorithms/src/spiral_matrix/spiral_matrix_clockwise_cycle.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <vector>
using namespace std;
void print_top_row(int x, int y, int X, int Y, vector<vector<int>>matrix) {
for (int i = y; i<= Y; ++i) cout<<matrix[x][i]<<" ";
}
void print_right_column(int x, int y, int X, int Y, vector<vector<int>>matr... |
code/mathematical_algorithms/src/square_free_number/square_free_number.c | //Program to check whether a number is square_free or not
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int isSquareFree(int n)
{
if(n % 2 == 0)
n /= 2;
if(n % 2 == 0)
return 0;
int i;
for(i = 3; i <= sqrt(n); i += 2)
{
if(n % i == 0)
{
n /= i;... |
code/mathematical_algorithms/src/square_free_number/square_free_number.cpp | //Program to check whether a number is square_free or not
#include <iostream>
#include <cmath>
bool isSquareFree(int n)
{
if (n % 2 == 0)
n /= 2;
if (n % 2 == 0)
return false;
for (int i = 3; i <= std::sqrt(n); i += 2)
if (n % i == 0)
{
n /= i;
if (n... |
code/mathematical_algorithms/src/square_free_number/square_free_number.py | # Program to check whether a number is square_free or not
from math import sqrt
def is_square_free(n):
if n % 2 == 0:
n = n / 2
if n % 2 == 0:
return False
for i in range(3, int(sqrt(n) + 1)):
if n % i == 0:
n = n / i
if n % i == 0:
retur... |
code/mathematical_algorithms/src/square_free_number/squarefreenumber.java | // Program to check whether a number is square_free or not
import java.util.Scanner;
class SquareFreeNumber{
static boolean isSquareFree(int n) {
if(n % 2 == 0)
n /= 2;
if(n % 2 == 0)
return false;
for(int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
n /= i;
... |
code/mathematical_algorithms/src/std/std.c | #include <stdio.h>
#include <math.h>
// calculate the mean of a given array having n elements
double
__mean(double arr[], size_t n)
{
double sum = 0;
for (size_t i = 0; i < n; i++) {
sum = sum + arr[i];
}
double mean = sum / n;
return (mean);
}
// calculate the standard deviation of a giv... |
code/mathematical_algorithms/src/std/std.cpp | #include <cmath>
template <typename T>
typename T::value_type mean(const T& container)
{
typename T::value_type result;
for (const auto& value : container)
result += value;
if (container.size() > 0)
result /= container.size();
return result;
}
template <typename T>
typename T::value_ty... |
code/mathematical_algorithms/src/std/std.go | package main
// Part of Cosmos by OpenGenus Foundation
import (
"fmt"
"math"
)
// Mean calculates the mean value of a given slice. If an empty slice is given
// it will return a zero mean by convention.
func Mean(x []float64) float64 {
sum := 0.0
n := len(x)
if n == 0 {
return sum
}
for i := 0; i < n; i++ {... |
code/mathematical_algorithms/src/std/std.js | function sd(arr) {
// calculate standard deviation of array of numbers
var arr_sum = 0;
var arr_square_sum = 0;
for (var i = 0; i < arr.length; ++i) {
arr_sum += arr[i]; // sum of values in array
arr_square_sum += arr[i] * arr[i]; // sum of squares of values in array
}
var arr_mean = arr_sum / arr.... |
code/mathematical_algorithms/src/std/std.py | # Part of Cosmos by OpenGenus Foundation
from math import sqrt
def __mean(array):
return float(sum(array)) / max(len(array), 1)
def __variance(array):
mean = __mean(array)
return __mean(map(lambda x: (x - mean) ** 2, array))
def std(array):
return sqrt(variance(array))
print(std([])) # 0.0
pr... |
code/mathematical_algorithms/src/steepest_descent/steepest_descent.cpp | /*
* The method of steepest descent
* -------------------
* An algorithm for finding the nearest local minimum of a function.
* It solves an equation in quadratic form: Ax = b where x is the values we seek.
* A is a matrix of size NxN, and b is a vector of N values.
*
* Time complexity
* ---------------
* O(e^... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.c | #include <stdio.h>
// Part of Cosmos by OpenGenus Foundation
int
sumOfDigits(int number)
{
int sum = 0;
while(number != 0) {
sum += (number % 10);
number /= 10;
}
return (sum);
}
int
main()
{
int num;
printf("Enter number to be summed: ");
scanf("%d", &num);
printf("\... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.cpp | //Part of Cosmos by OpenGenus Foundation
#include <iostream>
using namespace std;
long long int sum_of_digits(long long int n)
{
long long int sum = 0;
while (n != 0)
{
sum += n % 10; // summing the unit place digit of number n
n /= 10; // reducing the number by 10
}
return sum; ... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.cs | //Part of Cosmos by OpenGenus Foundation
using System;
class MainClass {
public static int sumDigits(long n) {
long sum = 0;
while (n > 0) {
sum += n % 10;
n = n / 10;
}
return Convert.ToInt32(sum);
}
public static void Main(String[] args){
Console.WriteLine("Enter... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.ex | defmodule Math do
def sum_of_digits(n) do
Enum.reduce(Integer.digits(n), fn(x, acc) -> x + acc end)
end
end
IO.puts Math.sum_of_digits(12345)
|
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.go | //Part of Cosmos by OpenGenus Foundation
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Print("Enter digits to sum sperated by a space:")
str, err := getline()
if err == nil {
fmt.Println("Here is the result:", sumNumbers(str))
}
}
func getline() (string, error) {
return... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.java | // Part of Cosmos by OpenGenus Foundation
public class SumOfDigits {
public static int sumDigits(long n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n = n / 10;
}
return sum;
}
}
|
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.js | /* Part of Cosmos by OpenGenus Foundation */
//Sum of Digits - Add all digits in a number
// returns the sum of digits or -1 on invalid input
//Val must be a positive whole number
function sumOfDigits(val) {
if (typeof val !== "number" || val !== Math.ceil(val) || val < 0) {
return -1;
}
let sum = 0;
whi... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* Calculates sum of digits in number
*
* @param int $num number
* @return int sum of digits in number
*/
function sum_of_digits(int $num)
{
$sum = 0;
$str = (string)$num;
$len = strlen($num);
for($i = 0; $i < $len; $i++) {
$sum +... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.py | # Part of Cosmos by OpenGenus Foundation
def sum_of_digits(number):
return sum(map(int, str(number)))
input_text = int(input("Input your digits: "))
print("Sum of your digits is: {0}".format(sum_of_digits(input_text)))
|
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.rb | ## Part of Cosmos by OpenGenus Foundation
def sum_of_digits(num)
num = num.abs
sum = 0
while num > 0
sum += num % 10
num /= 10
end
sum
end
|
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.rs | use std::io::{stdin, stdout, Write};
fn main() {
stdout().write_all(b"Input your digits: ").unwrap();
stdout().flush().unwrap();
let mut input_text = String::new();
stdin().read_line(&mut input_text).unwrap();
let sum: u32 = input_text.chars().filter_map(|s| s.to_digit(10)).sum();
println!("Sum... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits.swift | //
// sum_of_digits.swift
// test
//
// Created by Kajornsak Peerapathananont on 10/14/2560 BE.
// Copyright © 2560 Kajornsak Peerapathananont. All rights reserved.
//
//Part of Cosmos by OpenGenus Foundation
import Foundation
func sum_of_digits(number : String)->Int{
return number.characters.map({ char in
... |
code/mathematical_algorithms/src/sum_of_digits/sum_of_digits_with_recursion.c | //Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
//loop
int sumOfDigits(int number)
{
int sum = 0;
while(number != 0)
{
sum += (number % 10);
number /= 10;
}
return sum;
}
//recursive
int recurSumOfDigits(int number)
{
if(number == 0)
return 0;
return ((nu... |
code/mathematical_algorithms/src/taxicab_numbers/taxicab_numbers.java |
public class taxicab_numbers{
public static void main(String[] args){
taxicab(10);
}
public static void taxicab(int n){
int answer = 1; //potential answer
int amountFound = 1; // The number of cube additions found per answer
int pairCount = 0; // the pairs of cube ... |
code/mathematical_algorithms/src/taxicab_numbers/taxicab_numbers.py | # the function taxi_cab_numbers generates and returns n taxicab numbers along with the number pairs
def taxi_cab_numbers(n):
gen_num = 0
v = {}
c = {}
i = 0
while gen_num < n:
c[i] = i * i * i
for j in range(i):
s = c[j] + c[i]
if s in v:
gen_n... |
code/mathematical_algorithms/src/tower_of_hanoi/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)
This problem is done using recurssive approach.
Moving n disks from rod L to rod R using rod C, can be recurssively defined as:
1.) Moving n-1 disks ... |
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.c | #include <stdio.h>
// Part of Cosmos by OpenGenus Foundation
int moves = 0;
void hanoi(int disks, char A, char B, char C);
int
main()
{
int n; // Number of disks
printf("Enter the number of disks- ");
scanf("%d", &n);
hanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
printf("Total moves-... |
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.cpp | #include <iostream>
// Part of Cosmos by OpenGenus Foundation
#include <stack>
using namespace std;
// Stack[0] -> Source Stack
// Stack[1] -> Auxilliary Stack
// Stack[2] -> Destination Stack
// For visualisation, we are also going to store the disk number along with its size.
// So,the data type for the... |
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.go | package main
import "fmt"
func towerOfHanoi(n int, from, to, aux string) {
if n >= 1 {
towerOfHanoi(n-1, from, aux, to)
fmt.Printf("Move %d, from %s to %s\n", n, from, to)
towerOfHanoi(n-1, aux, to, from)
}
}
func main() {
towerOfHanoi(5, "A", "C", "B")
}
|
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.hs | -- Part of Cosmos by OpenGenus Foundation
hanoi :: Int -> String -> String -> String -> IO Int
hanoi 0 _ _ _ = return 0
hanoi x from to using = do
c1 <- hanoi (x-1) from using to
putStrLn ("Moving " ++ show x ++ " from " ++ from ++ " to " ++ to)
c2 <- hanoi (x-1) using to from
return (1+ c1 + c2)
|
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.java | import java.util.Scanner;
//Recursive algorithm
public class TowersOfHanoi {
public void solve(int n, String start, String auxiliary, String end) {
if (n == 1) {
System.out.println(start + " -> " + end);
} else {
solve(n - 1, start, end, auxiliary);
System.out.printl... |
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.js | /* Part of Cosmos by OpenGenus Foundation */
"use strict";
function towerOfHanoi(n, from_rod, to_rod, aux_rod) {
if (n >= 1) {
// Move a tower of n-1 to the aux rod, using the dest rod.
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
// Move the remaining disk to the dest peg.
console.log("Move disk... |
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.ml | (* Part of Cosmos by OpenGenus Foundation *)
let tower_of_hanoi n =
let rec move n from dest other =
if n <= 0 then () else (
move (n-1) from other dest;
print_endline (from ^ " -> " ^ dest);
move (n-1) other dest from)
in
move n "L" "R" "C"
;;
tower_of_hanoi 5;;
|
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.py | # Part of Cosmos by OpenGenus Foundation
moves = 0
def TowerOfHanoi(disks, A, B, C):
global moves
moves += 1
if disks == 1:
print("Move disk 1 from rod", A, "to rod", B)
return
TowerOfHanoi(disks - 1, A, C, B)
print("Move disk", disks, "from rod", A, "to rod", B)
TowerOfHanoi(d... |
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.rs | fn main() {
tower_of_hanoi(5,"A","C","B");
}
fn tower_of_hanoi(n:u32, from: &str, to: &str, aux: &str) {
if n >= 1 {
tower_of_hanoi(n-1, from, aux, to);
println!("Move {}, from: {} to from {}",n,from,to );
tower_of_hanoi(n-1,aux,to,from);
}
} |
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi.scala | import scala.collection.mutable.ArrayStack
object TowerOfHanoi extends App{
var size:Int = 5
var a = new ArrayStack[Int]
for(i <- (1 to size).reverse){
a += i
}
var b = new ArrayStack[Int]
var c = new ArrayStack[Int]
var count:Int = 0
def move(n:Int, source:ArrayStack[Int], target:ArrayStack[Int], auxiliary... |
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi_binary_solution.c | #include <stdio.h>
int main()
{
printf("Enter the number of Disks");
int n;
scanf("%d", &n);
for (int i = 1; i < (1 << n); i++)
printf("\nMove from Peg %d to Peg %d", (i & i - 1) % 3 + 1,
((i | i - 1) + 1) % 3 + 1);
return 0;
}
|
code/mathematical_algorithms/src/tower_of_hanoi/tower_of_hanoi_iterative.c | #include <stdio.h>
#include <math.h>
void
toh (int n) {
int steps, start, end, i;
steps = pow (2, n); // Minimum number of moves required
for (i = 1; i < steps; i ++) {
start = (i & (i-1)) % 3;
end = (1 + (i | (i-1))) % 3;
printf ("Disc %d shifted from %d to %d\n", i, start + 1, end + 1);
... |
code/mathematical_algorithms/src/tribonacci_numbers/tribonacci_numbers.c | #include <stdio.h>
int
main()
{
int n;
int a = 0,b = 1,c = 2,d;
printf("Enter a Number\n");
scanf("%d",&n);
printf("%d %d %d ",a,b,c);
for (int i = 0; i < n-3; i++) {
d = a + b + c;
printf("%d ",d);
a = b;
b = c;
c = d;
}
return (0);
} |
code/mathematical_algorithms/src/tribonacci_numbers/tribonacci_numbers.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
using namespace std;
int main()
{
int n, i;
int a = 0, b = 1, c = 2, d;
cout << "Enter a number\n";
cin >> n;
cout << a << " " << b << " " << c << " ";
for (i = 0; i < n - 3; i++)
{
d = a + b + c;
cout << d ... |
code/mathematical_algorithms/src/tribonacci_numbers/tribonacci_numbers.go | package main
import "fmt"
// Prints series of 'n' tribonacci numbers
func tribonacci(n int) {
a, b, c := 0, 1, 1
fmt.Printf("%d, %d, %d, ", a, b, c)
for i := 3; i < n; i++ {
d := a + b + c
a, b, c = b, c, d
fmt.Printf("%d, ", d)
}
}
func main() {
tribonacci(15)
}
|
code/mathematical_algorithms/src/tribonacci_numbers/tribonacci_numbers.java | import java.util.Scanner;
public class Tribonacci {
public static void printTribonacci(int n){
int a=0,b=0,c=1,temp;
if(n<1)
return;
System.out.print(a + " ");
if(n>1)
System.out.print(b + " ");
if(n>2)
System.out.print(c + " ");
... |
code/mathematical_algorithms/src/tribonacci_numbers/tribonacci_numbers.js | function tribonacci(n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 0;
} else if (n == 2) {
return 1;
}
return tribonacci(n - 3) + tribonacci(n - 2) + tribonacci(n - 1);
}
tribonacci(15); //1705
|
code/mathematical_algorithms/src/tribonacci_numbers/tribonacci_numbers.py | n = int(input())
a = []
a.append(0)
a.append(0)
a.append(1)
for i in range(3, n):
a.append(a[i - 1] + a[i - 2] + a[i - 3])
for i in a:
print(i)
|
code/mathematical_algorithms/src/tribonacci_numbers/tribonacci_numbers.rs | // Prints series of 'n' tribonacci numbers
fn tribonacci(n: i32) {
let mut a = 0;
let mut b = 1;
let mut c = 1;
print!("{}, {}, {}, ", a, b, c);
for _ in 3..n {
let d = a + b + c;
a = b;
b = c;
c = d;
print!("{}, ", d);
}
}
fn main() {
tribonacci(15... |
code/mathematical_algorithms/src/tribonacci_numbers/tribonnaci.java | import java.util.*;
class Tribonacci {
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int a[] = new int[n+1];
a[1]=0;
a[2]=0;
a[3]=1;
for (int i = 4; i <= n; i++)
{
a[i]=... |
code/mathematical_algorithms/src/tridiagonal_matrix/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Tridiagonal matrix
Collaborative effort by [OpenGenus](https://github.com/opengenus)
More information in this: [Tridiagonal matrix](https://en.wikipedia.org/wiki/Tridiagonal_matrix)
|
code/mathematical_algorithms/src/tridiagonal_matrix/tridiagonal_matrix.java | public class TridiagonalMatrix {
private static void TridiagonalMatrix(double matrix[][], int rows, int cols) {
double[][] output = new double[rows][cols + 1];
System.out.println("First step:");
//Initialization of initial values for subsequent cycles.
double y1 = matrix[0][0];
... |
code/mathematical_algorithms/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/mathematical_algorithms/test/test_exponentiation_by_squaring.c | #include <stdio.h>
#include "exponentiation_by_squaring.c"
int
main()
{
int num, exp;
printf("Enter Number \n");
scanf("%d", &num);
printf("Enter Exponent \n");
scanf("%d", &exp);
printf("Result: %d \n", power(num, exp));
return (0);
}
|
code/networking/src/README.md | # cosmos
Your personal library of every networking algorithm and code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/networking/src/determine_endianess/determine_endianess.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Determine if the machine is in Little Endian or Big Endian.
*/
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
bool isBigEndian(uint16_t input) {
//for example : if input = 0x0001, so it's stored as big endian. in little endian it'll be stored as 0x0100
... |
code/networking/src/determine_endianess/determine_endianess.sh | #!/bin/bash
#shell script to determine endianess of the machine
lscpu | grep Byte| cut -d ":" -f 2
#more portable code
#uncomment below lines if above command fails
#a=`echo -n I | od -to2 | awk 'FNR==1{ print substr($2,6,1)}'`
#if [[ "$a" -eq 1 ]]
#then
#echo "Little Endian"
#else
#echo "Big Endian"
#fi
|
code/networking/src/packetsniffer/README.md | ## Packet Sniffer (Packet Analyzer)
A packet analyzer (also known as a packet sniffer) is a computer program or piece of computer hardware that can intercept and log traffic that passes over a digital network or part of a network. Packet capture is the process of intercepting and logging traffic. As data streams flow ... |
code/networking/src/packetsniffer/packetsniffer.py | #!/usr/bin/python
import socket
import os
import sys
import struct
import binascii
import textwrap
import time
def wireshark_open(filename):
"""
Global Header
typedef struct pcap_hdr_s {
guint32 magic_number; /* magic number */ (4 bytes) I
guint16 version_major; /* major version ... |
code/networking/src/validate_ip/README.md | # VALIDATE IP
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;
Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid.
IPv6 addresses are repres... |
code/networking/src/validate_ip/ValidateIp.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.Arrays;
import java.util.regex.Pattern;
public class ValidateIp {
private static final Pattern ipv4pattern =
Pattern.compile("(?:(?:(?:[1-9][0-9]{0,2})|0)\\.){3}(?:(?:[1-9][0-9]{0,2})|0)");
private static final Pattern ipv6pattern = Pattern... |
code/networking/src/validate_ip/ipv4_check.go | package main
import (
"fmt"
"net"
)
func checkIP(ip string) bool {
netIP := net.ParseIP(ip)
if netIP.To4() == nil {
fmt.Printf("%v is not an IPv4 address\n", ip)
return false
}
fmt.Printf("%v is an IPv4 address\n", ip)
return true
}
func main() {
checkIP("1.2.3.4")
checkIP("216.14.49.185")
checkIP("1::... |
code/networking/src/validate_ip/is_valid_ip.php | <?php
function is_ipv4($str) {
$ret = filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
return $ret;
}
function is_ipv6($str) {
$ret = filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
return $ret;
}
|
code/networking/src/validate_ip/validate_connection_ipv4.py | import sys
from os import system
class checkip:
# Initilaize IP
def __init__(self, ip):
ip = ip.strip().split(".")
ip = [int(n) for n in ip]
# set input ip to correct form of IP
ip_correct = str(ip).strip("[]").replace(",", ".").replace(" ", "")
self.ip_correct = ip_co... |
code/networking/src/validate_ip/validate_ip.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Program to check if a given string is a valid IPv4 address or not.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define DELIM "."
/* return 1 if string contain only digits, else return 0 */
int
valid_digit(char *ip_str)
{
wh... |
code/networking/src/validate_ip/validate_ip.cc | #include <arpa/inet.h>
bool Config::validateIpAddress(const string &ipAddress)
{
struct sockaddr_in sa;
int result = inet_pton(AF_INET, ipAddress.c_str(), &(sa.sin_addr));
return result != 0;
}
// add drive / test code |
code/networking/src/validate_ip/validate_ip.rb | # Given an ip address, verify if it is a valid IPv4 address
def validate_ip(ip_addresss)
components = ip_addresss.split('.')
if components.length != 4
return false
else
components.each do |item|
return false unless item.to_i.between?(0, 255)
end
return true
end
end
# Correct IP address ... |
code/networking/src/validate_ip/validate_ip.sh | #!/bin/bash
read -p "ENter the IPv4 address " IP
for i in `seq 1 4`
do
arr[i]=`echo "$IP"|cut -d "." -f "$i"`
done
for i in `seq 1 4`
do
a=${arr[i]}
case "$a" in
[0-255])
flag=1
;;
*)
flag=0
;;
esac
done
if [[ "$flag" -eq 1 ]]
then
echo "Valid IP"
else
echo "Invalid IP"
fi
|
code/networking/src/validate_ip/validate_ip/validate_ipv4.c | /* This implementation reads in a file as argv[1] and checks if each line of the file is a valid IPv4 address.
Algorithm of the IPv4 validation is in the char *is_ipv4(char *ip_addr) function.
Implementation utilized inet_pton() and information about that function
from https://beej.us/guide/bgnet/html/multi/inet_ntop... |
code/networking/src/validate_ip/validate_ip/validate_ipv6.c | /* This implementation reads in a file as argv[1] and checks if each line of the file is a valid IPv6 address.
Algorithm of the IPv6 validation is in the char *is_ipv6(char *ip_addr) function.
Implementation utilized inet_pton() and information about that function
from https://beej.us/guide/bgnet/html/multi/inet_ntop... |
code/networking/src/validate_ip/validate_ipv4.js | function verify_ipv4(ip) {
const rx = /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/;
return ip.match(rx);
}
/*
Regex explanation:
^ start of string
(?!0) Assume IP cannot start with 0
(?!.*\.$) Make sure string does not end with a dot
(
(
1?\d?\d| A single digit, two digits, ... |
code/networking/src/validate_ip/validate_ipv4.py | #!/usr/bin/python3
# Check if an IP address conforms to IPv4 standards
def validate_ipv4(ip_addr):
ip_components = ip_addr.split(".")
if len(ip_components) != 4:
return False
else:
for component in ip_components:
if int(component) not in range(0, 255):
return Fals... |
code/networking/src/validate_ip/validate_ipv6.py | import socket
def validateIPv6(ip):
try:
socket.inet_pton(socket.AF_INET6, ip)
return True
except socket.error:
return False
print(validateIPv6("2001:cdba:0000:0000:0000:0000:3257:9652")) # True
print(validateIPv6("2001:cdbx:0000:0000:0000:0000:3257:9652")) # False
|
code/networking/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/numerical_analysis/adam_bashforth/src/adam_bashforth.py | from typing import Union, Callable, List
"""
The Adams–Bashforth methods allow us explicitly
to compute the approximate solution at an instant
time from the solutions in previous instants.
This module allows you compute approximations
using fourth-order Adams-Bashforth method.
Reference: https... |
code/numerical_analysis/bisection/src/Bisection Method.cpp | #include<bits/stdc++.h>
using namespace std;
/*
Program to Find Root of the equation x*x-2*x-2=0 by Bisection Method
First we take 2 values from function of the Equation (negative/positive) then place it in a and b;
then we check that if we assigned the right a and b
then we apply Bisection Method Formu... |
code/numerical_analysis/false_position/src/False Position.cpp | #include<bits/stdc++.h>
using namespace std;
/*
Program to Find Root of the equation x*x*x-x-1=0 by False Position Method
First we take 2 values from function of the Equation (negative/positive) then place it in a and b;
then we check that if we assigned the right a and b
then we apply False Position Fo... |
code/numerical_analysis/gauss_jacobi/src/Gauss Jacobi.cpp | #include<bits/stdc++.h>
using namespace std;
/*
Program to Find Root of the equation by Gauss Jacobi Method
First we need to take input of the size of matrix (example for X,Y,Z we need to take size of matrix value 3)
then we gradually input them serially (no need to type x,y,z. for -20x type -20 )
then... |
code/numerical_analysis/gauss_seidal/src/Gauss Seidal.cpp | #include<bits/stdc++.h>
using namespace std;
/*
Program to Find Root of the equation by Gauss Seidal Method
First we need to take input of the size of matrix (example for X,Y,Z we need to take size of matrix value 3)
then we gradually input them serially (no need to type x,y,z. for -20x type -20 )
then... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.