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. Sieve of Eratosthenes is a simple algorithm to find prime numbers. Though, there are better algorithms exist today, sieve of Eratosthenes is a great example of the sieve approach. <b>Algorithm</b> First of all algorithm requires a bit array isComposite to store n - 1 numbers: isComposite[2 .. n]. Initially the array contains zeros in all cells. During algorithm's work, numbers, which can be represented as k * p, where k ≥ 2, p is prime, are marked as composite numbers by writing 1 in a corresponding cell. Algorithm consists of two nested loops: outer, seeking for unmarked numbers (primes), and inner, marking primes' multiples as composites. <ul type="disc"> <li>For all numbers m: 2 .. n, if m is unmarked:</li> <ul type="circle"> <li> add m to primes list;</li> <li> mark all it's multiples, lesser or equal, than n (k * m ≤ n, k ≥ 2);</li> </ul> <li>otherwise, if m is marked, then it is a composite number.</li> </ul> <b>Modification</b> Let's notice, that algorithm can start marking multiples beginning from square of a found unmarked number. Indeed, For m = 2, algorithm marks 2 * 2 3 * 2 4 * 2 5 * 2 6 * 2 7 * 2 ... For m = 3, 2 * 3 were already marked on m = 2 step. For m = 5, 2 * 5 3 * 5 4 * 5 (= 10 * 2) were already marked on m = 2 and m = 3 steps. Strong proof is omitted, but you can easily prove it on your own. Modified algorithm is as following: <ul type="disc"> <li>For all numbers m: 2 .. √n, if m is unmarked:</li> <ul type="circle"> <li>add m to primes list;</li> <li>mark all it's multiples, starting from square, lesser or equal than n (k * m ≤ n, k ≥ m);</li> </ul> <li>otherwise, if m is marked, then it is a composite number;</li> <li>check all numbers in range √n .. n. All found unmarked numbers are primes, add them to list.</li> </ul> Collaborative effort by [OpenGenus](https://github.com/opengenus)
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 and 1 are not prime isPrime[0] = 0; isPrime[1] = 0; // Maintain a count of primes as we encounter them int count = 0; // We need a count of all primes as we move // This means we cannot iterate to root(max) for(i = 2; i <= max; ++i) { if(isPrime[i] == 1) { ++count; int j; // Set all multiples of i as not prime for(j = 2 * i; j <= max; j += i) isPrime[j] = 0; } } *primes = (int *)malloc(sizeof(int) * count); int j = 0; for(i = 0; i <= max; ++i) { if(isPrime[i] == 1) { (*primes)[j++] = i; } } return count; } int main() { int n = 100, i; int *primes = NULL; // Find primes up to n int size = sieve_of_eratosthenes(&primes, n); printf("Primes up to %d are:\n", n); for(i = 0; i < size; ++i) { printf("%d\n", primes[i]); } return 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<bool> prime(n + 1, true); for (int p = 2; p * p <= n; p++) // If prime[p] is not changed, then it is a prime if (prime[p] == true) // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) cout << p << " "; } // Driver Program to test above function int main() { int n; cout << "Enter the number"; cin >> n; cout << "Following are the prime numbers smaller " << " than or equal to " << n << endl; SieveOfEratosthenes(n); cout << "\n"; return 0; }
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}\n"); Console.WriteLine(string.Join(",", primes)); Console.ReadLine(); } private static int[] SieveOfEratosthenes(int n) { // create number list from 0 to n var numbers = Enumerable.Range(0, n + 1).Select(x => x).ToArray(); var lenRoot = Math.Sqrt(n); // go through all possible factors of numbers in the range bound inclusive by 2 and n for (var i = 2; i <= lenRoot; i++) { // skip numbers already blanked by a prime factor if (numbers[i] == 0) continue; for (int j = i * i; j < numbers.Length; j += i) { // blank out any multiple of i numbers[j] = 0; } } // return all numbers between 2 and n // these will be all primes in the range return numbers.Where(x => x > 1).ToArray(); } } }
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++ { if integers[i] == true { //Check all multiples of i for j := i * 2; j <= n; j += i { integers[j] = false } } } //Return all unchanged numbers (prime numbers) <= n var primes []int for i := 2; i <= n; i++ { if integers[i] == true { primes = append(primes, i) } } return primes }
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 exclude multiples of -- that number. go (x:xs) = x : (go $ filter (\n -> n `mod` x /= 0) xs) primes = eratosthenes main = do n <- getLine print $ take (read n :: Int) primes
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 not. int a=2; for(int i=0; i<n; i++){ //initialises all elements of checkPrime to true checkPrime[i] = true; } for(int i=a ; i*i<=n ; i++){ //outer for loop is to check whether a particular element has been marked, if no then it is taken if(checkPrime[i] == true){ for(int j=i*2 ; j<=n ; j=j+i){ // inner for loop marks the multiples of the element selected by the outer for loop checkPrime[j] = false; } } } for(int i=2 ; i<=n ; i++){ if(checkPrime[i] == true) System.out.println(i+" "); } } public static void main(String [] args){ System.out.println("Enter the upperBound:"); Scanner s=new Scanner(System.in); int n=s.nextInt(); erathosthenes ee = new erathosthenes(); ee.sieve(n); } }
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 and 1 // are not primes and do not need to be evaluated. this._storage = Array.from({ length: max - 1 }, (k, v) => v + 2); } _isPrime(num) { for (let i = 2; i < this._sqrtMax; i++) { if (num % i === 0 && num !== i) { return false; } } return true; } /** * start - determine all primes * @return {array} an array of all prime numbers from 2 to max. */ start() { this._storage = this._storage.filter(num => { return this._isPrime(num); }); return this._storage; } } //////////// // TESTS: // //////////// // All valid prime numbers up to 1000 const primeNums = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 ]; // Test cases: // All test cases should return "test-X is true" const testNums = [1, 30, 100, 300, 600, 1000]; testNums.forEach((max, idx) => { const sieve = new SieveOfEratosthenes(max); const allPrimes = sieve.start(); const diff = allPrimes.filter(num => { return primeNums.indexOf(num) === -1; }); console.log(`test-${idx} is ${diff.length === 0}`); });
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 ($i = 2; $i <= (int) sqrt($n); $i++) { if ($array[$i] === true) { for ($j = $i ** 2; $j <= $n; $j += $i) { $array[$j] = false; } } } return array_keys($array, true); } echo implode(', ', sieveOfEratosthenes(365));
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(input().rstrip())) except: sys.exit() print(primes[0]) print("\nComputations {}".format(primes[1]))
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) { while (primes[k] != true) k++; if (primes[i]) for (int j = i; j < n; j = j + i) if (j != i) primes[j] = false; } for (int i = 2; i < n; ++i) if (primes[i]) cout << i << ' '; cout << '\n'; }
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 (!min_divider[i]) { min_divider[i] = i; primes.push_back(i); } for (int p : primes) { if (p > n / i) break; min_divider[p * i] = p; } } return primes; } int main() { std::cout << "Enter the number:" << std::endl; int n; std::cin >> n; std::cout << "List of prime numbers less or equal than " << n << ":\n"; for (int num : sieve_linear(n)) std::cout << num << "\n"; return 0; }
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; ++i) { if (i == 0 || i == n) value += y[i]; else if (i % 2 != 0) value += 4 * y[i]; else value += 2 * y[i]; } value *= h / 3; return value; } int main() { cout << "Enter the lower limit"; cin >> x1; cout << "Enter the upper limit"; cin >> x2; cout << simpson(x1, x2)<< "\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, k = 1, 10, 20 f = lambda x: x + sqrt(x) result = simpson(f, a, b, k) result2 = quad(f, a, b) print(result) print(result2[0])
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 is %d :\n",smallest_digit(n)); return (0); }
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() { int n; cin >> n; cout << smallest_digit(n); return 0; }
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; } n /= 10; } return min; } public static void Main() { Console.Write("enter a number : "); int number; Int32.TryParse(Console.ReadLine(), out number); Console.WriteLine(smallestNumber(number)); } } }
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 n) { int min = n%10; n/=10; while(n!=0) { if(min>n%10) min=n%10; n/=10; } return min; } }
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(); return numbers[0]; }; console.log(smallest_digit_in_number(243245));
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 = [ [0, 0], [9, 9], [11, 1], [99, 9], [19, 1], [91, 1], [10000, 0], [1000090, 0], ]; foreach ($test_data as $test_case) { $input = $test_case[0]; $expected = $test_case[1]; $result = smallest_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/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(user_number)))
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_number}" end def is_a_number?(input) is_a_fixnum = input.is_a? Integer return false unless is_a_fixnum true end smallest_digit_in_number 92_345_678
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 ], [ 13 14 15 16 ] ]; Example Traversal: 1 → 2 → 3 → 4 ↓ 5 → 6 → 7 8 ↑ ↓ ↓ 9 10 ← 11 12 ↑ ↓ 13 ← 14 ← 15 ← 16 Example Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 */ // Recursive implementation of printing a matrix in clockwise spiral form // Informally, this function prints the outermost "ring" around the matrix, // in a clockwise fashion, and then prints the next outermost "ring", and so on // Arguments: // mat: a 2-dimensional vector of ints // // row_start/col_start: beginning index of matrix (i.e. 0, 0) // // row_end/col_end: ending index of matrix (a 0-based index!) // Ex. a 4 x 4 matrix would have an ending index of 3, 3 // a 5 x 6 matrix would have an ending index of 4, 5 // Time Complexity: O(m*n) // Space Complexity: O(1), 2-d vector is passed by reference void spiral_print(vector<vector<int> > &mat, int row_start, int col_start, int row_end, int col_end) { // check to see if we are "outside" the ring we are currently printing if (row_start > row_end || col_start > col_end) { return; } // Print top row for (int i = row_start; i <= col_end; i++) { cout << mat[row_start][i] << " "; } // Print rightmost column for (int i = row_start + 1; i <= row_end; i++) { cout << mat[i][col_end ] << " "; } // Print bottom row, only if this row hasn't been printed yet if (row_end != row_start) { for (int i = col_end - 1; i >= col_start; i--) { cout << mat[row_end][i] << " "; } } // Print leftmost column, only if this column hasn't been printed yet if (col_end != col_start) { for (int i = row_end - 1; i > row_start; i--) { cout << mat[i][col_start] << " "; } } // Function calls itself to print the next innermost "ring" spiral_print(mat, row_start + 1, col_start + 1, row_end - 1, col_end - 1); } // Driver int main() { // a 4x4 matrix vector<vector<int> > mat_a = { {1, 2, 3, 4}, { 12, 13, 14, 5}, { 11, 16, 15, 6}, { 10, 9, 8, 7} }; spiral_print(mat_a, 0, 0, 3, 3); cout << '\n'; // a 3x10 matrix vector<vector<int> > mat_b = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {21, 22, 23, 24, 25, 26, 27, 28, 29, 10}, {20, 19, 18, 17, 16, 15, 14, 13, 12, 11}}; spiral_print(mat_b, 0, 0, 2, 9); cout << '\n'; // a 12x4 matrix vector<vector<int> > mat_c = { {1, 2, 3, 4}, {28, 29, 30, 5}, {27, 48, 31, 6}, {26, 47, 32, 7}, {25, 46, 33, 8}, {24, 45, 34, 9}, {23, 44, 35, 10}, {22, 43, 36, 11}, {21, 42, 37, 12}, {20, 41, 38, 13}, {19, 40, 39, 14}, {18, 17, 16, 15}}; spiral_print(mat_c, 0, 0, 11, 3); cout << '\n'; }
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>>matrix) { for(int i = x; i<= X; ++i) cout<<matrix[i][Y]<<" "; } void print_bottom_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_left_column(int x, int y, int X, int Y, vector<vector<int>>matrix) { for(int i = X; i >= x; --i) cout<<matrix[i][y]<<" "; } void cartisian_cycle(vector<vector<int>>matrix) { int x = 0, y = 0; int X = matrix.size() - 1; int Y = matrix[0].size() - 1; while (true) { if (x > X || y > Y) break; print_top_row(x, y, X, Y, matrix); ++x; if (x > X || y > Y) break; print_right_column(x, y, X, Y, matrix); --Y; if (x > X || y > Y) break; print_bottom_row(x, y, X, Y, matrix); --X; if (x > X || y > Y) break; print_left_column(x, y, X, Y, matrix); ++y; } } /* Driver Code */ int main() { vector<vector<int>> a = { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; cartisian_cycle(a); vector<vector<int>> b = { {1,2,3}, {12,13,4}, {11,14,5}, {10,15,6}, {9,8,7} }; cartisian_cycle(b); return 0; }
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; if(n % i == 0) return 0; } } return 1; } int main() { int n; printf("Enter a number: "); scanf("%d",&n); if(isSquareFree(n)) printf("%d is square free number",n); else printf("%d is not a square free number",n); return 0; }
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 % i == 0) return false; } return true; } int main() { int n; std::cout << "Enter a number: "; std::cin >> n; if (isSquareFree(n)) std::cout << n << " is square free number"; else std::cout << n << " is not a square free number"; return 0; }
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: return False return True n = int(input("Enter a number ")) if is_square_free(n): print(str(n) + " is square free number") else: print(str(n) + " is not a square free number")
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; if (n % i == 0) return false; } } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a number"); int n = sc.nextInt(); if (isSquareFree(n)) System.out.println(n + " is square free number"); else System.out.println(n + " is not a square free number"); } }
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 given array having n elements double std(double arr[], size_t n) { double mean = __mean(arr, n); double std = 0; for (size_t i = 0; i < n; i++) { std = std + (arr[i] - mean) * (arr[i] - mean); } return (sqrt(std / n)); } int main() { double arr[] = { 12, 65, 91, 52, 18, 72 }; printf("%lf", std(arr, sizeof(arr) / sizeof(arr[0]))); // 28.41 return (0); }
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_type var(const T& container) { auto mu = mean(container); typename T::value_type result; for (const auto& value : container) { auto res = value - mu; result += res * res; } if (container.size() > 1) result /= container.size() - 1; return result; } template <typename T> typename T::value_type stdDev(const T& container) { return std::sqrt(var(container)); }
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++ { sum = sum + x[i] } return sum / float64(n) } // Variance calculates the variance from the mean of a given slice. If an empty // slice is given it will return a zero variance by convention. func Variance(x []float64) float64 { variance := 0.0 n := len(x) if n == 0 { return variance } mean := Mean(x) for i := 0; i < n; i++ { variance += (x[i] - mean) * (x[i] - mean) } return variance / float64(n) } // Std returns the standard deviation of a given slice. func Std(x []float64) float64 { return math.Sqrt(Variance(x)) } func main() { x := []float64{12, 65, 91, 52, 18, 72} fmt.Println(Std(x)) }
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.length; // this is E[X] var arr_square_mean = arr_square_sum / arr.length; // this is E[X^2] var variance = arr_square_mean - arr_mean * arr_mean; // Var(X) = E[X^2] - E[X]^2 return Math.sqrt(variance); } // tests: sd([12, 65, 91, 52, 18, 72]); // returns 28.41, as expected sd([-10.6]); // returns 0, as expected sd([-1, -1, 0, 1, 1]); // returns 0.8944, as expected
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 print(std([12, 65, 91, 52, 18, 72])) # 28.41...
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^-2), where e is an error we can accept (indicates how far we are from solution). * * Space complexity * ---------------- * O(2*N), where N is a size of matrix */ #include <iostream> #include <array> #include <cmath> /* * Evalutates euclidean norm */ template <long unsigned int S> double norm(const std::array<double, S> &x, const std::array<double, S> &y) { double result = 0; for (unsigned int i = 0; i < S; ++i) result += (x[i] - y[i]) * (x[i] - y[i]); return std::move(sqrt(result)); } /* * Adds up two matrix */ template <long unsigned int S> std::array<double, S> operator+(const std::array<double, S> &x, const std::array<double, S> &y) { std::array<double, S> result; for (unsigned int i = 0; i < S; ++i) result[i] = x[i] + y[i]; return std::move(result); } /* * Subtrack two matrix */ template <long unsigned int S> std::array<double, S> operator-(const std::array<double, S> &x, const std::array<double, S> &y) { std::array<double, S> result; for (unsigned int i = 0; i < S; ++i) result[i] = x[i] - y[i]; return std::move(result); } /* * Multiplication of matrix and constant value */ template <long unsigned int S> std::array<double, S> operator*(const double x, const std::array<double, S> &y) { std::array<double, S> result; for (unsigned int i = 0; i < S; ++i) result[i] = x * y[i]; return std::move(result); } /* * Multiplication of NxN and Nx1 matrix */ template <long unsigned int S> std::array<double, S> operator*(const std::array<std::array<double, S>, S> &A, const std::array<double, S> &b) { std::array<double, S> result = {0.0}; for (unsigned int i = 0; i < S; ++i) for (unsigned int j = 0; j < S; ++j) result[i] += A[i][j] * b[j]; return result; } /* * Method of Steepest Descent */ template <long unsigned int S> std::array<double, S> steepestdescent(const std::array<std::array<double, S>, S> &A, const std::array<double, S> &b, const double e = 0.0001, const double step = 0.1, const unsigned int IterMax = 10000) { std::array<double, S> x = {0.0}; unsigned int k = 0; do { std::array<double, S> xp = x; std::array<double, S> residual = b - A * xp; x = x + step * residual; if (norm(x, xp) < e) break; k += 1; } while (k < IterMax); return std::move(x); } /* * Overloads operator << to display NxN size array */ template <long unsigned int S> std::ostream &operator<<(std::ostream &stream, const std::array<std::array<double, S>, S> &A) { for (std::array<double, S> tmp : A) { for (double i : tmp) stream << i << '\t'; stream << '\n'; } return stream; } /* * Overloads operator << to display Nx1 size array */ template <long unsigned int S> std::ostream &operator<<(std::ostream &stream, const std::array<double, S> &x) { for (double i : x) stream << i << '\n'; return stream; } int main() { const long unsigned int S = 3; const std::array<std::array<double, S>, S> A = {1, -1, 1, 1, 1, 0, 1, 2, 0}; const std::array<double, S> b = {9, 1, -2}; std::array<double, S> x; std::array<double, S> tmp; // std::cout << "Maxtrix A:\n"<< A << '\n'; std::cout << "Vector b:\n" << b << '\n'; x = steepestdescent(A, b, 0.0000001); std::cout << "Result:\n" << x << '\n'; tmp = A * x; std::cout << "Ax = :\n" << tmp << '\n'; return 0; }
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("\nThe sum of digits is %d \n",sumOfDigits(num)); return (0); }
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; // returning the sum of digits of given number n } int main() { long long int n; cin >> n; cout << sum_of_digits(n); return 0; }
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 number to be summed"); long num = Convert.ToInt64(Console.ReadLine()); int sum = sumDigits(num); Console.WriteLine(string.Format("Sum of digits of {0} is {1}", num, sum) ); } }
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 bufio.NewReader(os.Stdin).ReadString('\n') } func sumNumbers(str string) float64 { var sum float64 for _, v := range strings.Fields(str) { i, err := strconv.ParseFloat(v, 64) if err != nil { fmt.Println(err) } else { sum += i } } return sum }
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; while (Math.floor(val) > 0) { sum += Math.floor(val % 10); val /= 10; } return sum; } // sumOfDigits_S accepts numbers as type 'number' or string function sumOfDigits_S(val) { if ( (typeof val !== "number" && typeof val !== "string") || +val !== Math.ceil(+val) || +val < 0 ) { return -1; } return val .toString() .split("") .reduce((t, cv) => { return t + +cv; }, 0); }
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 += (int)$str[$i]; } return $sum; } echo "sum of digits\n"; echo " 12345: " . sum_of_digits(12345) . "\n"; echo " 54321: " . sum_of_digits(54321) . "\n"; echo " 0: " . sum_of_digits(0) . "\n"; echo " 12: " . sum_of_digits(12) . "\n";
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 of your digits is: {}", 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 return Int(String(char))! }).reduce(0, +) }
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 ((number%10) + sumOfDigits(number/10)); } int main() { int num; printf("Enter number to be summed: "); scanf("%d", &num); printf("Digits summed: %d\n", sumOfDigits(num)); printf("Digits summed: %d", recurSumOfDigits(num)); }
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 additions while( (pairCount) < n){ //resetting amount counter fir every new potential answer there is amountFound = 0; //Going through all the values to the potential answer seeing if it has 2 pairs. for(int x = 1; x < Math.pow(answer,((double)1)/3); x++){ for(int y = x + 1; y < Math.pow(answer,((double)1)/3); y++){ if (((double)Math.pow(x,3) + (double)Math.pow(y,3)) == (double)answer){ amountFound++; //^ means that an answer has been found so the one below this \/ checks if it was a pair or not. if (amountFound == 2){ pairCount ++; System.out.println((pairCount) + " " + answer); } } } } //increasing the potential answer by one answer++; } } }
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_num = gen_num + 1 yield (s, (j, i), v[s]) v[s] = (j, i) i = i + 1 def print_taxi_numbers(n): for x in taxi_cab_numbers(n): print(x) if __name__ == "__main__": print_taxi_numbers(10)
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 from rod L to rod C. 2.) Moving nth disk from rod L to rod R. 3.) Moving n-1 disks from rod C to rod R. The recussion stops when n becomes 1 which is just moving a particular disk. Source : Wikipedia Disk positions may be determined more directly from the binary (base-2) representation of the move number (the initial state being move #0, with all digits 0, and the final state being with all digits 1), using the following rules: There is one binary digit (bit) for each disk. The most significant (leftmost) bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it's on the final peg (right peg if number of disks is odd and middle peg otherwise). The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk. A bit with the same value as the previous one means that the corresponding disk is stacked on top the previous disk on the same peg. (That is to say: a straight sequence of 1s or 0s means that the corresponding disks are all on the same peg). A bit with a different value to the previous one means that the corresponding disk is one position to the left or right of the previous one. Whether it is left or right is determined by this rule: Assume that the initial peg is on the left. Also assume "wrapping" – so the right peg counts as one peg "left" of the left peg, and vice versa. Let n be the number of greater disks that are located on the same peg as their first greater disk and add 1 if the largest disk is on the left peg. If n is even, the disk is located one peg to the right, if n is odd, the disk located one peg to the left (in case of even number of disks and vice versa otherwise). For example, in an 8-disk Hanoi: Move 0 = 00000000. The largest disk is 0, so it is on the left (initial) peg. All other disks are 0 as well, so they are stacked on top of it. Hence all disks are on the initial peg. Move 28 − 1 = 11111111. The largest disk is 1, so it is on the middle (final) peg. All other disks are 1 as well, so they are stacked on top of it. Hence all disks are on the final peg and the puzzle is complete. Move 21610 = 11011000. The largest disk is 1, so it is on the middle (final) peg. Disk two is also 1, so it is stacked on top of it, on the middle peg. Disk three is 0, so it is on another peg. Since n is odd (n = 1), it is one peg to the left, i.e. on the left peg. Disk four is 1, so it is on another peg. Since n is odd (n = 1), it is one peg to the left, i.e. on the right peg. Disk five is also 1, so it is stacked on top of it, on the right peg. Disk six is 0, so it is on another peg. Since n is even (n = 2), the disk is one peg to the right, i.e. on the left peg. Disks seven and eight are also 0, so they are stacked on top of it, on the left peg. The source and destination pegs for the mth move can also be found elegantly from the binary representation of m using bitwise operations. To use the syntax of the C programming language, move m is from peg (m & m - 1) % 3 to peg ((m | m - 1) + 1) % 3, where the disks begin on peg 0 and finish on peg 1 or 2 according as whether the number of disks is even or odd. Another formulation is from peg (m - (m & -m)) % 3 to peg (m + (m & -m)) % 3. Furthermore, the disk to be moved is determined by the number of times the move count (m) can be divided by 2 (i.e. the number of zero bits at the right), counting the first move as 1 and identifying the disks by the numbers 0, 1, 2 etc. in order of increasing size. This permits a very fast non-recursive computer implementation to find the positions of the disks after m moves without reference to any previous move or distribution of disks. The operation, which counts the number of consecutive zeros at the end of a binary number, gives a simple solution to the problem: the disks are numbered from zero, and at move m, disk number count trailing zeros is moved the minimal possible distance to the right (circling back around to the left as needed).
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- %d\n", moves); return (0); } void hanoi(int disks, char A, char B, char C) { moves++; if (disks==1) { printf("Move disk 1 from rod %c to rod %c \n", A, B); return; } hanoi(disks -1 , A, C, B); printf("Move disk %d from rod %c to rod %c \n", disks, A, B); hanoi(disks - 1, C, B, A); }
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 stack is pair<int,int> // The pair will correspond to < disk size,disk number > stack<pair<int, int>> Stack[3]; // Tower of Hanoi Function // Parameters are (A,B,C,N) // A -> Source Stack Number // B -> Auxilliary Stack Number // C -> Destination Stack Number // N -> Number of disks to be transferred from the Source Stack to the Destination Stack void Tower_of_Hanoi(int A, int B, int C, int N) { if (N == 0) return; Tower_of_Hanoi(A, C, B, N - 1); // Transferring N-1 disks from stack A to B via C pair<int, int> curr_disk = Stack[A].top(); // Nth Disk , still present in the Source stack int sz = curr_disk.first; // Size of the Nth Disk int number = curr_disk.second; // Disk Number of the Nth Disk Stack[A].pop(); // Poppped the Nth Disk from the Source stack Stack[C].push(curr_disk); cout << "Transferred Disk : Size " << sz << " and Number " << number << " from Stack " << A << " to " << C << endl; Tower_of_Hanoi(B, A, C, N - 1); } int main() { // N is the number of disks int source stack int N; // Taking the input for these parameters cout << "Enter the number of disks \n"; cin >> N; cout << "Enter the size of the disks \n"; cout << "Note they must be in descending order \n \n"; for (int i = N; i >= 1; i--) { int sz; cin >> sz; Stack[0].push(make_pair(sz, i)); cout << "Disk : Size " << sz << " and Number " << i << " pushed into the Source Stack \n"; } //Executing the Tower of Hanoi Function cout << " \n Tower of Hanoi \n"; cout << " ----------------------------- \n \n"; Tower_of_Hanoi(0, 1, 2, N); return 0; }
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.println(start + " -> " + end); solve(n - 1, auxiliary, start, end); } } public static void main(String[] args) { TowersOfHanoi towersOfHanoi = new TowersOfHanoi(); System.out.print("Enter number of discs: "); Scanner scanner = new Scanner(System.in); int discs = scanner.nextInt(); towersOfHanoi.solve(discs, "A", "B", "C"); } }
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 from Tower ", from_rod, " to Tower ", to_rod); // Move the tower of `n-1` from the `aux_rod` to the `dest rod` using the `source rod`. towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } return; } towerOfHanoi(3, "A", "C", "B");
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(disks - 1, C, B, A) # Driver code n = int(input("Enter the number of disks- ")) TowerOfHanoi(n, "A", "C", "B") print("Total moves required = " + str(moves))
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:ArrayStack[Int]){ if(n > 0){ move(n-1, source, auxiliary, target) target += source.pop println(s"$a, $b, $c") move(n-1, auxiliary, target, source) count += 1 } } move(size, a, c, b) println(count) }
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); } } int main() { int n; printf ("Enter the number of discs : "); scanf ("%d", &n); toh(n); return (0); }
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 << " "; a = b; b = c; c = d; } return 0; }
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 + " "); for(int i=3;i<n;i++) { temp = a + b + c; a = b; b = c; c = temp; System.out.print(c + " "); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter n >> "); int n = sc.nextInt(); printTribonacci(n); } }
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]=a[i-1]+a[i-2]+a[i-3]; } for(int i=1;i<=n;i++){ System.out.println(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]; double alpha = -matrix[0][1] / y1; alpha = new BigDecimal(alpha).setScale(2, RoundingMode.HALF_DOWN).doubleValue(); double betta = matrix[0][cols - 1] / y1; betta = new BigDecimal(betta).setScale(2, RoundingMode.HALF_DOWN).doubleValue(); //Future alpha double alphaNext; //Calculating count for alpha, the next string it ++ to find needing alpha. int countA = 0; int countC = 2; output[0][0] = y1; output[1][0] = alpha; output[0][1] = betta; output[0][cols] = matrix[0][cols - 1]; for (int i = 1; i < cols - 1; i++) { double b_i = matrix[i][i]; double alhpa_i = matrix[i][countA]; alhpa_i = new BigDecimal(alhpa_i).setScale(2, RoundingMode.HALF_DOWN).doubleValue(); double y_i = b_i + alhpa_i * alpha; y_i = new BigDecimal(y_i).setScale(2, RoundingMode.HALF_DOWN).doubleValue(); if (countC < cols - 1) { //Count second alpha for future alphaNext = -matrix[i][countC] / y_i; alphaNext = new BigDecimal(alphaNext).setScale(2, RoundingMode.HALF_DOWN).doubleValue(); output[countC][i] = alphaNext; } else { alphaNext = 1; } double betta_i = (matrix[i][cols - 1] - alhpa_i * betta) / y_i; betta_i = new BigDecimal(betta_i).setScale(2, RoundingMode.HALF_DOWN).doubleValue(); output[i][i] = y_i; output[i][countC] = betta_i; output[i][cols] = matrix[i][cols - 1]; countA++; countC++; alpha = alphaNext; betta = betta_i; } printArray(output, rows, cols+1); System.out.println("Second step:"); ArrayList<Double> arrayList = new ArrayList<>(); //Find the last element Betta double x = output[rows - 1][cols - 1]; int countAlpha = rows - 1; int countBetta = rows - 1; arrayList.add(x); for (int j = cols - 2; j > 0; j--) { double alpha_i = output[countAlpha][j - 1]; double x_i = alpha_i * x + output[countBetta - 1][j]; x_i = new BigDecimal(x_i).setScale(2, RoundingMode.HALF_DOWN).doubleValue(); arrayList.add(x_i); x = x_i; countAlpha--; countBetta--; } System.out.println(arrayList); } 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(); } public static void main(String[] args) { double[][] myMatrix = {{9.0, 5.0, 0.0, 0.0, 0.0, 4.0}, {3.0, 7.0, 1.0, 0.0, 0.0, 4.0}, {0.0, 5.0, 11.0, 2.0, 0.0, 4.0}, {0.0, 0.0, 5.0, 6.0, 4.0, 4.0}, {0.0, 0.0, 0.0, 4.0, 5.0, 2.0}}; int rows = myMatrix.length; int cols = myMatrix[2].length; System.out.println("Original matrix: "); printArray(myMatrix, rows, cols); TridiagonalMatrix(myMatrix, rows, cols); } }
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 /* pointer to the first byte of input */ uint8_t* Byte = (uint8_t*)&input; /* First byte is 0x01 */ if (*Byte) return false; /* First byte is 0x00 */ return true; } int main() { uint16_t input = 1; if(isBigEndian(input)) printf("Big Endian\n"); else printf("Little Endian\n"); return 0; }
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 across the network, the sniffer captures each packet and, if needed, decodes the packet's raw data, showing the values of various fields in the packet, and analyzes its content according to the appropriate RFC or other specifications. A packet analyzer used for intercepting traffic on wireless networks is known as a wireless analyzer or WiFi analyzer. A packet analyser can also be referred to as a network analyzer or protocol analyzer though these terms also have other meanings. [Text of Wikipedia](https://en.wikipedia.org/wiki/Packet_analyzer) ## Algorithm ```python #!/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 number */ (2 bytes) H guint16 version_minor; /* minor version number */ (2 bytes) H gint32 thiszone; /* GMT to local correction */ (4 bytes) guint32 sigfigs; /* accuracy of timestamps */ (4 bytes) I guint32 snaplen; /* max length of captured packets, in octets */ (4 bytes) I guint32 network; /* data link type */ (4 bytes) I } pcap_hdr_t; ''' name = filename n,ext = name.split('.') if ext != 'pcap': return wshark_file = open(filename, "wb") wshark_file.write(struct.pack("@IHHIIII", 0xa1b2c3d4, 2, 3, 0, 0, 65535, 1)) return wshark_file def wireshark_write(file_object, data): ''' Record (Packet) Header typedef struct pcaprec_hdr_s { guint32 ts_sec; /* timestamp seconds */ (4 bytes) guint32 ts_usec; /* timestamp microseconds */ (4 bytes) guint32 incl_len; /* number of octets of packet saved in file */ (4 bytes) guint32 orig_len; /* actual length of packet */ (4 bytes) } pcaprec_hdr_t; ''' ts_sec, ts_usec = str(time.time()).split('.') ts_sec = int(ts_sec) ts_usec = int(ts_usec) incl_len = len(data) file_object.write(struct.pack('@ I I I I', ts_sec, ts_usec, incl_len, incl_len)) file_object.write(data) def wireshark_close(file_object): file_object.close() def met_http_header(recv, tam): print("\t\t\tHTTP Header:") try: http_dado = recv.decode('utf-8') except: http_dado = recv i = http_dado.split('\n') s = '\n'.join('\t\t\t\t\t' + lin for lin in textwrap.wrap(http_dado, 90)) print("\t\t\t\tHTTP Data:\n%s"%s) return http_dado def met_tcp_header(recv, tam): ''' 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ''' tcp_header = struct.unpack("!2H2I4H", recv[:20]) source_port = tcp_header[0] destination_port = tcp_header[1] sequence_number = tcp_header[2] acknowledgment_number = tcp_header[3] ''' Data Offset: This indicates where the data begins. The TCP header (even one including options) is an integral number of 32 bits long. ''' data_offset = tcp_header[4] >> 12 reserved = (tcp_header[4] >> 6) & 0x03ff flag = tcp_header[4] &0x003f urgent_pointer = flag & 0x0020 acknowledgment = flag & 0x0010 push = flag & 0x0000 reset = flag & 0x0004 sync = flag & 0x0002 fin = flag & 0x0001 window = tcp_header[5] check_sum = tcp_header[6] urgent_pointer = tcp_header[7] dado = recv[data_offset*4:tam] print ("\t\tTCP Header:") print ("\t\t\tSource Port: %hu, Destination Port: %hu" % (source_port, destination_port)) print ("\t\t\tSequence Number: %hu, Acknowlodgment Number: %hu, Data Offset: %hu" % (sequence_number,acknowledgment_number, data_offset)) print ("\t\t\tReserved: %hu" %reserved) print ("\t\t\tFlags:") print ("\t\t\t\tUrgent Pointer: %hu, Acknowledgment: %hu") % (urgent_pointer, acknowledgment) print ("\t\t\t\tPush: %hu, Reset: %hu" % (push, reset)) print ("\t\t\t\tSync: %hu, Fin: %hu" % (sync, fin)) print ("\t\t\tWindow Size: %hu, Check Sum: %hu"%(window, check_sum)) dado = ' '.join('{:02x}'.format(ord(i)) for i in dado) s = '\n'.join('\t\t\t\t' + l for l in textwrap.wrap(dado, 90)) print ("\t\t\tData:\n%s"%s) #recv = recv[20:] recv = recv[data_offset:] return recv, source_port, destination_port def met_udp_header(recv, tam): ''' 0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | Source | Destination | | Port | Port | +--------+--------+--------+--------+ | | | | Length | Checksum | +--------+--------+--------+--------+ | | data octets ... +---------------- ... ''' udp_header = struct.unpack("!4H", recv[:8]) source_port = udp_header[0] destination_port = udp_header[1] length = udp_header[2] check_sum = udp_header[3] print ("\t\tUDP Header:") print ("\t\t\tSource Port: %hu, Destination Port: %hu" % (source_port, destination_port)) print ("\t\t\tLength: %hu, Check Sum: %hu" %(length, check_sum)) recv = recv[8:] return recv def met_ip_header(recv): ''' 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Version| IHL |Type of Service| Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identification |Flags| Fragment Offset | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Time to Live | Protocol | Header Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Destination Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ''' ip_header = struct.unpack("!6H4s4s", recv[:20]) type_of_service = ip_header[0] & 0x00ff version = ip_header[0] >> 12 ''' IHL : Internet header length (32 bits) ''' ihl = (ip_header[0] >> 8) & 0x0f total_len = ip_header[1] identification = ip_header[2] flags = ip_header[3] >> 13 n = flags >> 1 m = flags & 0x1 offset = ip_header[3] & 0x1fff time = ip_header[4] >> 8 protocolo = ip_header[4] & 0x00ff checksum = ip_header[5] end_maquina_saida = socket.inet_ntoa(ip_header[6]) end_maquina_destino = socket.inet_ntoa(ip_header[7]) if protocolo == 17: prox = "UDP" elif protocolo == 6: prox = "TCP" else: prox = 'nul' print ("\tIP Header:") print ("\t\tVersion: %hu, IHL: %hu" % (version, ihl)) print ("\t\tType of Service: %hu, Total Length: %hu, Identification: %hu" % (type_of_service, total_len, identification)) print ("\t\tNo Frag: %hu, More Frag: %hu" % (n, m)) print ("\t\tFragment Offset: %hu, Time to Live: %hu" % (offset, time)) print ("\t\tNext Protocol: %hu[%s]" % (protocolo,prox)) print ("\t\tCheck Sum: %hu" % checksum) print ("\t\tIP Source: %s, IP Dest: %s" % (end_maquina_saida, end_maquina_destino)) tam = total_len - (ihl*32)/8 recv = recv[(ihl*32)/8:] return recv, prox, tam def met_ethernet_header(recv): ip = False # The firs parameter is the mac destination (6 octets) # When using '(number)s' we have the number of bytes wanted et_header = struct.unpack("!6s6sH", recv[:14]) end_maquina_saida = binascii.hexlify(et_header[1]) end_maquina_destino = binascii.hexlify(et_header[0]) protocolo = et_header[2] >> 8 print ("Ethernet Header:") print ("\tMAC address dest:\t%s:%s:%s:%s:%s:%s" % (end_maquina_destino[0:2], end_maquina_destino[2:4], end_maquina_destino[4:6], end_maquina_destino[6:8], end_maquina_destino[8:10], end_maquina_destino[10:12])) print ("\tMAC address de source:\t%s:%s:%s:%s:%s:%s" % (end_maquina_saida[0:2], end_maquina_saida[2:4], end_maquina_saida[4:6], end_maquina_saida[6:8], end_maquina_saida[8:10], end_maquina_saida[10:12])) print ("\tProtocolo:\t%s" %hex(protocolo)) #IPv4 == 0X0800 if protocolo == 8: ip = True recv = recv[14:] return recv, ip def main(): '''Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-b yte swap operation.''' '''socket.PF_PACKET to send and recieve messages, below the internet protocol layer The process must be run with root access''' ''' When using socket.bind(()) we will redirect the access to an especific port I am using socket.RAW, so i dont want to bind my connection to a port''' sniffer = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x3)) wireshark_file = wireshark_open('aux.pcap') while True: recv = sniffer.recv(65535) wireshark_write(wireshark_file, recv) dados_novos, ip = met_ethernet_header(recv) if ip: dados_novos, prox, tam = met_ip_header(dados_novos) if prox == "TCP": dados_novos, src, dest = met_tcp_header(dados_novos, tam) if src == 80 or dest == 80: dados_novos = met_http_header(dados_novos, tam) elif prox == "UDP": dados_novos = met_udp_header(dados_novos, tam) wireshark_close(wireshark_file) main() ``` ## Usage ```shell # python packetSniffer.py ``` - At the end of the execution of the analyzer, will have a file with name 'aux.pcap'. You can execute this file with wireshark to obtain more information about the tracking. ## Protocols - ***Ethernet***: The header of the ethernet frame contains the MAC addresses of destination and source and the data with headers of another protocol. In my packet analyzer, I always analyze the internet protocol. - ***IPv4***: The IPv4 protocol is used for packet-switched networks. Is responsible for addressing the hosts, and route data from a source to a host. Each datagram has a header and a payload (data to transport). Nest the payload into a packet with header is called encapsulation. - ***TCP***: The TCP is a protocol of the transport layer. It functionality involves reliability, error verification, and others. This protocol provides a communication service at an intermediate level between an application program and the Internet Protocol. It is an abstraction of the network connection to the application. - ***UDP***: Is the most simple protocol of the transport layer. UDP uses a communication without connection complexity. Provides checksums for data integrity and port numbers for addressing different functions at the source and destination of the datagram. ## Protocol Datagrams ### ***Ethernet Frame*** ![Ethernet Datagram](img/ethernet.png) ### ***IPv4 Frame*** ![IP Frame](img/ip.png) ### ***TCP Frame*** ![TCP Frame](img/tcp.png) ### ***UDP Frame*** ![UDP Frame](img/udp.png)
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 number */ (2 bytes) H guint16 version_minor; /* minor version number */ (2 bytes) H gint32 thiszone; /* GMT to local correction */ (4 bytes) guint32 sigfigs; /* accuracy of timestamps */ (4 bytes) I guint32 snaplen; /* max length of captured packets, in octets */ (4 bytes) I guint32 network; /* data link type */ (4 bytes) I } pcap_hdr_t; """ name = filename n, ext = name.split(".") if ext != "pcap": return wshark_file = open(filename, "wb") wshark_file.write(struct.pack("@IHHIIII", 0xA1B2C3D4, 2, 3, 0, 0, 65535, 1)) return wshark_file def wireshark_write(file_object, data): """ Record (Packet) Header typedef struct pcaprec_hdr_s { guint32 ts_sec; /* timestamp seconds */ (4 bytes) guint32 ts_usec; /* timestamp microseconds */ (4 bytes) guint32 incl_len; /* number of octets of packet saved in file */ (4 bytes) guint32 orig_len; /* actual length of packet */ (4 bytes) } pcaprec_hdr_t; """ ts_sec, ts_usec = str(time.time()).split(".") ts_sec = int(ts_sec) ts_usec = int(ts_usec) incl_len = len(data) file_object.write(struct.pack("@ I I I I", ts_sec, ts_usec, incl_len, incl_len)) file_object.write(data) def wireshark_close(file_object): file_object.close() def met_http_header(recv, tam): print("\t\t\tHTTP Header:") try: http_dado = recv.decode("utf-8") except: http_dado = recv i = http_dado.split("\n") s = "\n".join("\t\t\t\t\t" + lin for lin in textwrap.wrap(http_dado, 90)) print("\t\t\t\tHTTP Data:\n%s" % s) return http_dado def met_tcp_header(recv, tam): """ 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ """ tcp_header = struct.unpack("!2H2I4H", recv[:20]) source_port = tcp_header[0] destination_port = tcp_header[1] sequence_number = tcp_header[2] acknowledgment_number = tcp_header[3] """ Data Offset: This indicates where the data begins. The TCP header (even one including options) is an integral number of 32 bits long. """ data_offset = tcp_header[4] >> 12 reserved = (tcp_header[4] >> 6) & 0x03FF flag = tcp_header[4] & 0x003F urgent_pointer = flag & 0x0020 acknowledgment = flag & 0x0010 push = flag & 0x0000 reset = flag & 0x0004 sync = flag & 0x0002 fin = flag & 0x0001 window = tcp_header[5] check_sum = tcp_header[6] urgent_pointer = tcp_header[7] dado = recv[data_offset * 4 : tam] print("\t\tTCP Header:") print( "\t\t\tSource Port: %hu, Destination Port: %hu" % (source_port, destination_port) ) print( "\t\t\tSequence Number: %hu, Acknowlodgment Number: %hu, Data Offset: %hu" % (sequence_number, acknowledgment_number, data_offset) ) print("\t\t\tReserved: %hu" % reserved) print("\t\t\tFlags:") print("\t\t\t\tUrgent Pointer: %hu, Acknowledgment: %hu") % ( urgent_pointer, acknowledgment, ) print("\t\t\t\tPush: %hu, Reset: %hu" % (push, reset)) print("\t\t\t\tSync: %hu, Fin: %hu" % (sync, fin)) print("\t\t\tWindow Size: %hu, Check Sum: %hu" % (window, check_sum)) dado = " ".join("{:02x}".format(ord(i)) for i in dado) s = "\n".join("\t\t\t\t" + l for l in textwrap.wrap(dado, 90)) print("\t\t\tData:\n%s" % s) # recv = recv[20:] recv = recv[data_offset:] return recv, source_port, destination_port def met_udp_header(recv, tam): """ 0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | Source | Destination | | Port | Port | +--------+--------+--------+--------+ | | | | Length | Checksum | +--------+--------+--------+--------+ | | data octets ... +---------------- ... """ udp_header = struct.unpack("!4H", recv[:8]) source_port = udp_header[0] destination_port = udp_header[1] length = udp_header[2] check_sum = udp_header[3] print("\t\tUDP Header:") print( "\t\t\tSource Port: %hu, Destination Port: %hu" % (source_port, destination_port) ) print("\t\t\tLength: %hu, Check Sum: %hu" % (length, check_sum)) recv = recv[8:] return recv def met_ip_header(recv): """ 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Version| IHL |Type of Service| Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identification |Flags| Fragment Offset | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Time to Live | Protocol | Header Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Destination Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ """ ip_header = struct.unpack("!6H4s4s", recv[:20]) type_of_service = ip_header[0] & 0x00FF version = ip_header[0] >> 12 """ IHL : Internet header length (32 bits) """ ihl = (ip_header[0] >> 8) & 0x0F total_len = ip_header[1] identification = ip_header[2] flags = ip_header[3] >> 13 n = flags >> 1 m = flags & 0x1 offset = ip_header[3] & 0x1FFF time = ip_header[4] >> 8 protocolo = ip_header[4] & 0x00FF checksum = ip_header[5] end_maquina_saida = socket.inet_ntoa(ip_header[6]) end_maquina_destino = socket.inet_ntoa(ip_header[7]) if protocolo == 17: prox = "UDP" elif protocolo == 6: prox = "TCP" else: prox = "nul" print("\tIP Header:") print("\t\tVersion: %hu, IHL: %hu" % (version, ihl)) print( "\t\tType of Service: %hu, Total Length: %hu, Identification: %hu" % (type_of_service, total_len, identification) ) print("\t\tNo Frag: %hu, More Frag: %hu" % (n, m)) print("\t\tFragment Offset: %hu, Time to Live: %hu" % (offset, time)) print("\t\tNext Protocol: %hu[%s]" % (protocolo, prox)) print("\t\tCheck Sum: %hu" % checksum) print("\t\tIP Source: %s, IP Dest: %s" % (end_maquina_saida, end_maquina_destino)) tam = total_len - (ihl * 32) / 8 recv = recv[(ihl * 32) / 8 :] return recv, prox, tam def met_ethernet_header(recv): ip = False # The firs parameter is the mac destination (6 octets) # When using '(number)s' we have the number of bytes wanted et_header = struct.unpack("!6s6sH", recv[:14]) end_maquina_saida = binascii.hexlify(et_header[1]) end_maquina_destino = binascii.hexlify(et_header[0]) protocolo = et_header[2] >> 8 print("Ethernet Header:") print( "\tMAC address dest:\t%s:%s:%s:%s:%s:%s" % ( end_maquina_destino[0:2], end_maquina_destino[2:4], end_maquina_destino[4:6], end_maquina_destino[6:8], end_maquina_destino[8:10], end_maquina_destino[10:12], ) ) print( "\tMAC address de source:\t%s:%s:%s:%s:%s:%s" % ( end_maquina_saida[0:2], end_maquina_saida[2:4], end_maquina_saida[4:6], end_maquina_saida[6:8], end_maquina_saida[8:10], end_maquina_saida[10:12], ) ) print("\tProtocolo:\t%s" % hex(protocolo)) # IPv4 == 0X0800 if protocolo == 8: ip = True recv = recv[14:] return recv, ip def main(): """Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-b yte swap operation.""" """socket.PF_PACKET to send and recieve messages, below the internet protocol layer The process must be run with root access""" """ When using socket.bind(()) we will redirect the access to an especific port I am using socket.RAW, so i dont want to bind my connection to a port""" sniffer = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x3)) wireshark_file = wireshark_open("aux.pcap") while True: recv = sniffer.recv(65535) wireshark_write(wireshark_file, recv) dados_novos, ip = met_ethernet_header(recv) if ip: dados_novos, prox, tam = met_ip_header(dados_novos) if prox == "TCP": dados_novos, src, dest = met_tcp_header(dados_novos, tam) if src == 80 or dest == 80: dados_novos = met_http_header(dados_novos, tam) elif prox == "UDP": dados_novos = met_udp_header(dados_novos, tam) wireshark_close(wireshark_file) main()
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 represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases). However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid. Example: ``` ##IPv4 - 172.16.254.1 - 10.10.23.54 ##IPv6 - 2001:0db8:85a3:0:0:8A2E:0370:7334 - 02001:0db8:85a3:0000:0000:8a2e:0370:7334
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.compile("(?:(?:(?:[0-9a-fA-F]{1,4})):){7}(?:(?:[0-9a-fA-F]{1,4}))"); public static void main(String[] args) { assert (isValid("172.16.254.1")); assert (!isValid("172.16.254.01")); assert (isValid("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); assert (isValid("2001:db8:85a3:0:0:8A2E:0370:7334")); assert (!isValid("02001:0db8:85a3:0000:0000:8a2e:0370:7334")); assert (!isValid("2001:0db8:85a3::8A2E:0370:7334 ")); } private static boolean isValid(String addr) { if (addr.contains(".")) { return isValidv4(addr); } if (addr.contains(":")) { return isValidv6(addr); } return false; } private static boolean isValidv4(String addr) { if (!ipv4pattern.matcher(addr).matches()) { return false; } return Arrays.stream(addr.split("\\.")).noneMatch(s -> Integer.parseInt(s) > 255); } private static boolean isValidv6(String addr) { return ipv6pattern.matcher(addr).matches(); } }
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::16") checkIP("260.00.00.130") }
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_correct self.ip = ip self.flag = 1 # Check if number of octed are correct or not def check_octed(self): if len(self.ip) != 4: print("worng number of octed") self.flag = 0 return # Check if each octed number are in rang 0 to 255 def check_digit(self): for i in range(4): if not (0 <= self.ip[i] <= 255): print(self.ip[i], " is not in range ") print("IP", self.ip_correct, " is NOT valid") self.flag = 0 return # If correct print confiramtion if self.flag == 1: print("IP", self.ip_correct, " is valid") # Check if current system is connected to IP or not def check_connection(self): if self.flag == 1: exit_code = system("ping -c1 -s1 -W1 " + self.ip_correct) if exit_code != 0: print("IP ", self.ip_correct, " is not up") else: print("IP ", self.ip_correct, " is up") ip = input() ipn = checkip(ip) ipn.check_octed() ipn.check_digit() ipn.check_connection()
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) { while (*ip_str) { if (*ip_str >= '0' && *ip_str <= '9') ++ip_str; else return (0); } return (1); } /* return 1 if IP string is valid, else return 0 */ int is_valid_ip(char* ip_str) { int i, num, dots = 0; char *ptr; if (ip_str == NULL) return (0); /* See following link for strtok() http://pubs.opengroup.org/onlinepubs/009695399/functions/strtok_r.html */ ptr = strtok(ip_str, DELIM); if (ptr == NULL) return (0); while (ptr) { /* after parsing string, it must contain only digits */ if (!valid_digit(ptr)) return (0); num = atoi(ptr); /* check for valid IP */ if (num >= 0 && num <= 255) { /* parse remaining string */ ptr = strtok(NULL, DELIM); if (ptr != NULL) ++dots; } else return (0); } /* valid IP string must contain 3 dots */ if (dots != 3) return (0); return (1); } /* main: for testing */ int main(void) { char ip_correct[] = "172.31.255.255"; char ip_incorrect[] = "192.168.2.300"; assert(is_valid_ip(ip_correct)); assert(!is_valid_ip(ip_incorrect)); return (0); }
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 example p validate_ip('123.123.123.123') # Incorrect IP address example p validate_ip('1234.123')
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_ntopman.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> char* is_ipv4(char *ip_addr); char* is_ipv4(char *ip_addr) { char *ans = ""; struct sockaddr_in sa; ans = inet_pton(AF_INET, ip_addr, &(sa.sin_addr)) ? "yes" : "no"; return ans; } int main(int argc, char *argv[]) { ssize_t n; char *line = NULL; char *ip_addr; size_t size = 32; FILE *fp; const char *filename = argv[1]; fp = fopen(filename, "r"); if (!fp) { fprintf(stderr, "Error in opening the file!\n"); exit(1); } while ((n = getline(&line, &size, fp)) != -1) { if (line[n-1] == '\n') { line[n-1] = '\0'; ip_addr = (char *) malloc(n-2); strncpy(ip_addr, line, n-2); } else { ip_addr = (char *) malloc(n); strncpy(ip_addr, line, n); } printf("Is '%s' valid IPv4? \n%s\n", ip_addr, is_ipv4(ip_addr)); } fclose(fp); return(0); }
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_ntopman.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> char* is_ipv6(char *ip_addr); char* is_ipv6(char *ip_addr) { char *ans = ""; struct sockaddr_in6 sa_6; ans = inet_pton(AF_INET6, ip_addr, &(sa_6.sin6_addr)) ? "yes" : "no"; return ans; } int main(int argc, char *argv[]) { ssize_t n; char *line = NULL; char *ip_addr; size_t size = 32; FILE *fp; const char *filename = argv[1]; fp = fopen(filename, "r"); if (!fp) { fprintf(stderr, "Error in opening the file!\n"); exit(1); } while ((n = getline(&line, &size, fp)) != -1) { if (line[n-1] == '\n') { line[n-1] = '\0'; ip_addr = (char *) malloc(n-2); strncpy(ip_addr, line, n-2); } else { ip_addr = (char *) malloc(n); strncpy(ip_addr, line, n); } printf("Is '%s' valid IPv6? \n%s\n", ip_addr, is_ipv6(ip_addr)); } fclose(fp); return(0); }
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, or 100-199 25[0-5]| The numbers 250-255 2[0-4]\d The numbers 200-249 ) \.|$ the number must be followed by either a dot or end-of-string - to match the last number ){4} Expect exactly four of these $ end of string */ // testing let ips = [ "1.2.3.4", "11.11.11.11", "123.123.123.123", "255.250.249.0", "1.12.123.255", "127.0.0.1", "1.0.0.0", "0.1.1.1", "01.1.1.1", "012.1.1.1", "1.2.3.4.", "1.2.3\n4", "1.2.3.4\n", "259.0.0.1", "123.", "1.2.3.4.5", ".1.2.3.4", "1,2,3,4", "1.2.333.4", "1.299.3.4" ]; ips.forEach(function(s) { if (verify_ipv4(s)) { console.log("valid: " + s); } else { console.log("invalid: " + s); } });
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 False return True if __name__ == "__main__": valid_IP = "192.168.1.1" invalid_IP = "31.2.2" assert validate_ipv4(valid_IP) == True assert validate_ipv4(invalid_IP) == False
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://www.sciencedirect.com/science/article /pii/S0898122110007777#:~:text=The%20Adams%E2%80%93Bashforth %20methods%20allow,by%20means%20of%20Newton's%20method. """ class AdamBashforth: """ This class provides methods to compute the approximation solution of functions with Adam-Bashforth Predictor/Corrector methods. >>> adam = AdamBashforth() >>> adam.predict("1 + y**2", [0, 0.2, 0.4, 0.6], [0, 0.2027, 0.4228, ... 0.6841],0.2) 1.023375031 >>> adam.predict("(x+y)/2", [0, 0.5, 1, 1.5], [2, 2.636, 3.595, 4.968],0.5) 6.87078125 >>> adam.correct() 6.873104492187499 >>> adam.predict(lambda x, y: 1 + y**2, [0, 0.2, 0.4, 0.6], [0, 0.2027, ... 0.4228, 0.6841],0.2) 1.023375031 """ def predict( self, function: Union[Callable[[float, float], float], str], x_points: List[float], y_points: List[float], h_val: float, ) -> float: """ Use Adam-Bashford predictor method to compute the approximation of the function whose differential equation is given by dy/dx = function(x, y) at x = x_points[3]+h_val. """ self.y_points = y_points self.x_points = x_points self.h_val = h_val if len(x_points) != 4 and len(y_points) != 4: raise Exception( "x_points and \ y_points must be lists of 4 values respectively" ) if isinstance(function, str): def func_(x, y): return eval(function.replace("x", str(x)).replace("y", str(y))) elif hasattr(function, "__call__"): func_ = function else: raise Exception("func_ must be a callable object or a string") self.func_ = func_ self.pred = y_points[3] + (h_val / 24) * ( (55 * func_(x_points[3], y_points[3])) - (59 * func_(x_points[2], y_points[2])) + (37 * func_(x_points[1], y_points[1])) - (9 * func_(x_points[0], y_points[0])) ) return self.pred def correct(self) -> float: """ Compute a corrected value of the prediction from the `predict` method. """ func_ = self.func_ x = self.x_points y = self.y_points h = self.h_val corrected = y[3] + (h / 24) * ( 9 * func_(x[3] + h, self.pred) + (19 * func_(x[3], y[3])) - (5 * func_(x[2], y[2])) + (func_(x[1], y[1])) ) return corrected if __name__ == "__main__": import doctest doctest.testmod()
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 Formula then we iterate it N'th Time */ double func(double x) { return x*x-2*x-2; } int main() { int n=20,i; float a,b,x,y; cout<<"Here is The Equation : \n\n x*x-2*x-2=0 \n\n"; cout<<"Enter Right Value for A and B : \n"; cin>>a>>b; if(func(a)<0 && func(b)>0) { for(i=1;i<n;i++) { x=(a+b)/2; y=(x*x-2*x-2); if(y==0)cout<<"Steps Taken "<<i<<" x="<<x<<endl; else if(y>0) { a=a; b=x; cout<<"Steps Taken "<<i<<" x="<<x<<endl; } else { a=x; b=b; cout<<"Steps Taken "<<i<<" x="<<x<<endl; } } } else { cout << "You have not Assigned right A and B\n"; } return 0; }
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 Formula then we iterate this similar way of bisection */ double func(double x) { return x*x*x-x-1; } int main() { int n=20,i; float a,b,x,y; cout<<"Here is The Equation : \n\n x*x*x-x-1=0 \n\n"; cout<<"Enter Right Value for A and B : \n"; cin>>a>>b; if (func(a) * func(b) >= 0) { cout << "You have not Assigned right A and B\n"; return 0; } for(i=1;i<n;i++) { x=((a*func(b)-b*func(a))/(func(b)-func(a))); y=func(x); if(y==0)cout<<"Steps Taken "<<i<<" X="<<x<<"\n"; else if(y>0) { a=a; b=x; cout<<"Steps Taken "<<i<<" X="<<x<<"\n"; } else { a=x; b=b; cout<<"Steps Taken "<<i<<" X="<<x<<"\n"; } } return 0; }
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 we take input of foremost right value (example 20X+2Y+6Z = 28) foremost right 28 will be taken as input) then we take initial value of x,y,z which is 0,0,0; then we take how many number of steps we need (10 or 15 steps is enough for all type of equation) then Done */ int main(void) { float a[10][10], b[10], x[10], y[10]; int n = 0, m = 0, i = 0, j = 0; cout << "Enter size of 2D array(Square matrix) : "; cin >> n; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { cout << "Enter values no :(" << i << ", " << j << ") "; cin >> a[i][j]; } } cout << "\nEnter Values to the right side of equation\n"; for (i = 0; i < n; i++) { cout << "Enter values no :(" << i << ", " << j << ") "; cin >> b[i]; } cout << "Enter initial values of x\n"; for (i = 0; i < n; i++) { cout << "Enter values no. :(" << i<<"):"; cin >> x[i]; } cout << "\nEnter the no. of iteration : "; cin >> m; while (m > 0) { for (i = 0; i < n; i++) { y[i] = (b[i] / a[i][i]); for (j = 0; j < n; j++) { if (j == i) continue; y[i] = y[i] - ((a[i][j] / a[i][i]) * x[j]); x[i] = y[i]; } cout<<i+1<<" "<<y[i]; } cout << "\n"; m--; } return 0; }
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 we take input of foremost right value (example 20X+2Y+6Z = 28) foremost right 28 will be taken as input) then we take initial value of x,y,z which is 0,0,0; then we take how many number of steps we need (10 or 15 steps is enough for all type of equation) then Done */ int main(void) { float a[10][10], b[10], m[10], n[10]; int p = 0, q = 0, i = 0, j = 0; cout << "Enter size of 2D array(Square matrix) : "; cin >> p; for (i = 0; i < p; i++) { for (j = 0; j < p; j++) { cout << "a[" << i << "," << j << "]="; cin >> a[i][j]; } } cout << "\nEnter values to the right side of equation\n"; for (i = 0; i < p; i++) { cout << "b[" << i << "," << j << "]="; cin >> b[i]; } cout << "Enter initial values of x\n"; for (i = 0; i < p; i++) { cout << "x:[" << i<<"]="; cin >> m[i]; } cout << "\nEnter the no. of iteration : "; cin >> q; while (q> 0) { for (i = 0; i < p; i++) { n[i] = (b[i] / a[i][i]); for (j = 0; j < p; j++) { if (j == i) continue; n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j]); m[i] = n[i]; } cout<<"x"<<i + 1 << "="<<n[i]<<" "; } cout << "\n"; q--; } return 0; }