text:
"""
# Euclid's Algorithm for GCD

greatest common divisor (GCD) is the greatest positive integer that able to divide all provided number evenly without remainder

# Reference
- Greatest Common Divisor -- https://brilliant.org/wiki/greatest-common-divisor/

# Example
```julia
gcd_euclid_algorithm([30, 12, 6]) # returns 6
gcd_euclid_algorithm([13, 48]) # returns 1
gcd_euclid_algorithm([2, 4, 6, 8, 16]) # returns 2
```

"""
function gcd_euclid_algorithm(arr::Vector{N})where N<:Integer

    result = arr[1]

    for i in 2:length(arr)
        result = find_gcd(result,arr[i])
        if result == 1
            break
         end
    end

    return result
end

function find_gcd(number1::Int,number2::Int)::Int
    while number2!=0
        number1, number2 = number2, number1 % number2
    end

    return number1
end

ext: jl

max_stars_repo_name: gohpeijin/Julia

max_issues_repo_name: gohpeijin/Julia

max_forks_repo_name: gohpeijin/Julia

lm_label:
1. YES
2. YES


text:
# 3x3 matrix A
a = [5 -3 11; 5 6 22; 8 19 0]
println("Matrix A = ", a)

# 3x3 matrix B
b = [12 3 -4; 5 16 9; 8 -3 4]
println("Matrix B = ", b)

# Task 1: addition and subtraction
println("\n============ Task 1: matrix addition and subtraction ============\n")
# expected results
c_add_exp = [17 0 7; 10 22 31; 16 16 4]
c_sub_exp = [-7 -6 15; 0 -10 13; 0 22 -4]

c_add = a + b
print("A+B = ", c_add)
c_sub = a - b
print("A-B = ", c_sub)

println("Does addition work as expected? ", c_add == c_add_exp)
println("Does subtracttion work as expected? ", c_sub == c_sub_exp)

# Task 2: matrix multiplications
println("\n============ Task 2: matrix multiplication ============\n")
c_mult_ab = a * b
c_mult_ba = b * a

println("A * B = ", c_mult_ab)
println("B * A = ", c_mult_ba)
println("==> A*B != B*A because rows from the first matrix will be multiplied with the columns from the seconds matrix. If those rows and columns are in different order, different values will result.")

# Task 3: matrix division
println("\n============ Task 3: matrix division ============\n")
c_diff_1 = a / b
println("A/B = ", c_diff_1)
c_diff_2 = a \ b
println("A\\B = ", c_diff_2)
println("==> A/B != A\\B, because the '\\' operator divides inverse which means that A\\B == B/A")

# Task 4: Single matrix operations
println("\n============ Task 4: single matrix operations ============\n")
a_incr = a + 1
println("A+1 = ", a_incr)
a_decr = a - 1
println("A-1 = ", a_decr)
a_double = a * 2
println("A*2 = ", a_double)
a_half = a / 2
println("A/2 = ", a_half)

# Task 5: matrix and vector multiplication
println("\n============ Task 5: matrix and vector multiplication ============\n")
# 3x4 matrix D
d = [5 -3 11 5; 6 22 8 19; 1 5 8 11]
println("Matrix D = ", d)
# 4x vector V
v = [2, 6, 9, 12]
println("Vector V = ", v)
result = d * v
println("D*V = ", result)
println("==> The result from the multiplication of a 3x4 matrix with a 4-dimensional vector is a 3-dimensional vector!")

max_stars_repo_name: DominicSchiller/osmi-module-datascience

max_issues_repo_name: DominicSchiller/osmi-module-datascience

max_forks_repo_name: DominicSchiller/osmi-module-datascience


text:
"""
    sieve_of_eratosthenes(n::Int64)

The Sieve of Eratosthenes is one of the historical algorithms dedicated to finding all
prime numbers up to any given limit. The algorithm is split into four steps:

1. Create a list of sequential integers from 2 to n.
2. Define initially `p=2` as the first prime number.
3. Reconstruct all multiple combinations from `p=2`.
4. Find the first number greater than p in the array that is not listed. Then decided:
	* If no number exists => stop.
	* `p` becomes equal to the number and go back to step 3.

For more information see: [https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)

# Arguments
- `n::Int64`: Number of elements

# Examples
```julia-repl
julia> import ClassicAlgorithmsCollections
julia> ClassicAlgorithmsCollections.sieve_of_eratosthenes(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
```
"""
function sieve_of_eratosthenes(n::Int64)
    prime = fill(true, n)
    p = 2
    while p^2 <= n

        if prime[p] == true

            # Update all multiples of p
            for i in p^2:p:n
                prime[i] = false
            end

        end
        p += 1
    end
    result = zeros(Int64, count(prime) - 1)
    i = 1
    for p in 2:n
        if prime[p]
            result[i] = p
            i += 1
        end
    end
    return result
end

max_stars_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_issues_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_forks_repo_name: Anselmoo/ClassicAlgorithmsCollections


text:
"""
Julia program to find the N'th Lucas Number.
Lucas Numbers is a sequence similar to Fibonacci numbers and is defined
as the sum of its two immediately previous terms.
The first and second numbers in Lucas sequence are 2 and 1 respectively.
"""

function lucas_num(n)
    l1 = 2
    l2 = 1
    if(n == 0)
        return l1
    end

    for i in (2:n)
        next = l1 + l2
        l1 = l2
        l2 = next
    end
    return l2
end

print("Enter the value of n(where you need the nth lucas number): ")
n = readline()
n = parse(Int, n)
if(n < 0)
    print("Invalid Value of n !!!")
    exit()
end
res = lucas_num(n)
print("The $n'th Lucas Number is $res.")

"""
Time Complexity - O(n), where `n` is the given number.
Space Complexity - O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE I

Enter the value of n(where you need the nth lucas number): 25
The 25'th Lucas Number is 167761.
"""

max_issues_repo_name: adarshnjena/NeoAlgo

max_forks_repo_name: adarshnjena/NeoAlgo


text:
"""
    bedaPusat(f, a; delta=10^-9)
adalah fungsi yang digunakan untuk mencari nilai turunan `f` pada titik `a`
menggunakan formula beda pusat. Secara default, digunakan nilai toleransi `delta=1e-9`

# Examples
```jl
julia> sol,flag,L = bedaPusat(sin,pi/3);

julia> sol
0.4999999999921733

julia> flag
0

julia> L
6×2 Array{Float64,2}:
 0.420735  NaN
 0.499167    0.0784316
 0.499992    0.000824583
 0.5         8.24996e-6
 0.5         8.24996e-8
 0.5         8.26006e-10

julia> sol,flag,L = bedaPusat(sin,pi/3,delta=1e-12);

julia> sol
0.4999999999588666

julia> flag
2

julia> L
8×2 Array{Float64,2}:
 0.420735  NaN
 0.499167    0.0784316
 0.499992    0.000824583
 0.5         8.24996e-6
 0.5         8.24996e-8
 0.5         8.26006e-10
 0.5         3.33067e-11
 0.5         3.33067e-10
```
return solusi `sol` dengan `flag` bernilai 0 jika toleransi terpenuhi, `flag`
bernilai 1 jika maksimum iterasi tercapai, `flag` bernilai 2 jika error minimum
telah tercapai namun tidak memenuhi toleransi. Serta, matriks `L` yang berisi
catatan tiap iterasi `[sol, error]`
"""
function bedaPusat(f, a; delta=10^-9)
  maxi = 15;
  flag = 1;
  h    = 1;
  D = (f(a+h)-f(a-h))/(2*h);
  E = NaN;
  sol = NaN
  for k = 1:maxi
    h = h/10;
    D = [D (f(a+h)-f(a-h))/(2*h)]
    E = [E abs(D[k+1]-D[k])]
    if E[k+1]<delta
      flag = 0;
      sol = D[end];
      break
    end
    if E[k+1]>E[k]
      sol  = D[k];
      flag = 2;
      break
    end
  end
  L = [D' E'];
  return sol, flag, L
end


text:
"""
    factorial_iterative(n)

Finds factorial of a number using Iterative method

# Example
```julia
factorial_iterative(5)      # returns 120
factorial_iterative(0.1)    # returns error
factorial_iterative(-1)     # returns error
```
# Reference
- factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial

Contributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)
"""
function factorial_iterative(n)
    if n != trunc(n) || n < 0
        throw(error("factorial_iterative() only accepts non-negative integral values"))
    end
    factorial::BigInt = 1
    map(i -> factorial *= i, 1:n)
    return factorial
end

"""
    factorial_recursive(n)

Finds factorial of anumber using recursive method

# Example
```julia
factorial_recursive(5)      # returns 120
factorial_recursive(0.1)    # returns error
factorial_recursive(-1)     # returns error
```
# Reference
- factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial

Contributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)
"""
function factorial_recursive(n)
    if n != trunc(n) || n < 0
        throw(error("factorial_iterative() only accepts non-negative integral values"))
    end
    if n == 0 || n == 1
        return 1
    else
        factorial::BigInt = n * factorial_recursive(n - 1)
        return factorial
    end
end

max_stars_repo_name: ashwani-rathee/Julia

max_issues_repo_name: ashwani-rathee/Julia

max_forks_repo_name: ashwani-rathee/Julia


text:
# Finding greatest common divisor using Euclidean Algorithm
function gcdFunction(a, b)
    if a == 0
        return b
    end
    return gcdFunction(b % a, a)
end
function power(x, y, m)
    if y == 0
        return 1
    end
    p = power(x, y / 2, m) % m
    p = (p * p) % m

    if y % 2 == 0
        return p
    else
        return (x * p) % m
    end
end
function modInverse(a, m)
    gcd = gcdFunction(a, m)

    if gcd != 1
        return -1
    else
        return power(a, m - 2, m)
    end
end

a = 3
m = 11

ans = modInverse(a, m)

if ans == -1
    println("Inverse doesn't exist")
else
    println("Modular multiplicative inverse is $(ans-1)")
end

# Output

#Modular multiplicative inverse is 4

max_stars_repo_name: rajatenzyme/Coding-Journey-

max_issues_repo_name: rajatenzyme/Coding-Journey-

max_forks_repo_name: rajatenzyme/Coding-Journey-


text:
# function _swap_rows(A::AbstractMatrix{NB}, i::T, nlines::T) where {T<:Int, NB<:Number}
    # for n ∈ (i+1):nlines        # iterate in lines below to check if could be swap
        # if A[n,i] ≠ 0.0         # condition to swap row
            # L = copy(A[i,:])    # copy line to swap
            # A[i,:] = A[n,:]     # swap occur
            # A[n,:] = L
            # break
        # end
    # end
    # return A
# end

"""
    gauss_jordan(A::AbstractMatrix{T}) where T<:Number

Gaussian elimination, also known as row reduction, is an algorithm for solving systems of linear equations.
It consists of a sequence of operations performed on the corresponding matrix of coefficients.
This method can also be used to compute the rank of a matrix, the determinant of a square matrix, and the inverse of an invertible matrix.
https://en.wikipedia.org/wiki/Gaussian_elimination

# Examples/Tests
```julia
julia> M1 = [1 2 3; 4 5 6];
julia> M2 = [1 2 3; 4 8 12];

julia> @test gauss_jordan(M1) == [1 0 -1; 0 1 2]        # Test Passed
julia> @test_throws AssertionError gauss_jordan(M2)     # Test Passed - Thrown: AssertionError
```

# Contributed By:- [AugustoCL](https://github.com/AugustoCL)
"""
function gauss_jordan(A::AbstractMatrix{T}) where {T<:Number}

    # convert to float to avoid InexactError: Int64()
    (T <: Integer) && (A = convert.(Float64, A))

    # check if matrix is singular
    m, n = size(A)
    if m == n
        @assert det(A) ≠ 0.0 "Must insert a non-singular matrix"
    else
        @assert det(A[:,1:end-1]) ≠ 0.0 "Must insert a non-singular matrix or a system matrix [A b]"
    end

    # execute the gauss-jordan elimination
    for i ∈ axes(A, 1)
        (A[i,i] == 0.0) && map([A,i,m]) do (x,y,z)
            for n ∈ (y+1):z                             # check if need swap rows -> this came from function `_swap_rows` (commented above)
                if x[n,y] ≠ 0.0                         # Since it is used only once, an anonymous function with do-block should suffice.
                    L = copy(x[y,:])
                    x[y,:] = x[n,:]
                    x[n,:] = L
                    break
                end
            end
            return x
        end

        @. A[i,:] = A[i,:] ./ A[i,i]                    # divide pivot line by pivot element

        for j ∈ axes(A, 1)                              # iterate each line for each pivot column, except pivot line
            if j ≠ i                                    # jump pivot line
                @. A[j,:] = A[j,:] - A[i,:]*A[j,i]      # apply gauss jordan in each line
            end
        end
    end

    return A
end

max_stars_repo_name: eliascarv/Julia

max_issues_repo_name: eliascarv/Julia

max_forks_repo_name: eliascarv/Julia


text:
#####################
# Correlation calculated as given in:
# Reference
# Biddle Consulting Group (2019) http://www.biddle.com/documents/bcg_comp_chapter2.pdf
using Statistics # library for the function mean(X), the mean value of the vector X.

# We can use any symbol for our functions.
# Let's us the mathematical symbols for  square root and sum.
√ = sqrt
∑ = sum

# Given the vectors,
X1 = [2.5, 3.6, 1.2, 0.8, 4.0, 3.4]
X2 = [1.2, 1.0, 1.8, 0.9, 3.0, 2.2]
X3 = [8.0, 15.0, 12.0, 6.0, 8.0, 10.0]

# We want to find  the correlations between the variable vectors:
# X1 and X2, X1 and X3, X2 and X3 using correlation
# coefficient approach.

# First we implement the funktion for sample standard deviation as:
"""
    S(X)
Compute the sample standard deviation of X

# Example
```julia-repl
julia> X1 = [2.5, 3.6, 1.2, 0.8, 4.0, 3.4]
6-element Array{Float64,1}:
 2.5
 3.6
 1.2
 0.8
 4.0
 3.4
julia> S(X1)
1.3272779161376365
```
"""
S(X)= √( ∑( map(i -> (X[i]-mean(X))^2, 1:length(X))) / (length(X)-1))

# Next we implement the biased estimate of covariance as:
"""
    S(X, Y)
Compute the biased estimate of covariance betweem X and Y

# Example
```julia-repl
julia> X1 = [2.5, 3.6, 1.2, 0.8, 4.0, 3.4]
6-element Array{Float64,1}:
 2.5
 3.6
 1.2
 0.8
 4.0
 3.4

 julia> X2 = [1.2, 1.0, 1.8, 0.9, 3.0, 2.2]
 6-element Array{Float64,1}:
  1.2
  1.0
  1.8
  0.9
  3.0
  2.2

 julia> S(X1, X2)
 0.5736666666666667
```
"""
S(X,Y)= ∑( map(i -> ((X[i]-mean(X))*(Y[i]-mean(Y))), 1:length(X))) / (length(X)-1)

ρ(X,Y)=S(X,Y)/(S(X)*S(Y))

print("\n\nCorrelation between X1 anx X2 is ", ρ(X1, X2))
print("\n\nCorrelation between X1 anx X3 is ", ρ(X1, X3))
print("\n\nCorrelation between X2 anx X3 is ", ρ(X2, X3))
print("\n\n")


text:
#=
P32 (**) Determine the greatest common divisor of two positive integer numbers.
Use Euclid's algorithm.
Example:
* (gcd 36 63)
9
=#

function gcd(a, b)
    if b == 0
        a
    else
        gcd(b, mod(a, b))
    end
end

@assert gcd(36, 63) == 9
@assert gcd(108, 30) == 6
@assert gcd(32, 5) == 1

println("Tests passed: JL-32.jl")


text:
## Figures for the Quadratic Equation slides
using Plots
using LaTeXStrings
pyplot() # nicer output
theme(:dark)
# Need for 3d arrow
using PyPlot

##
A = [3 -1.5; -1.5 2]
b = [-1; 1]
quadratic_ls(A,b) = x-> 0.5*x'*A*x - x'*b
ezsurf(x, y, f) = begin
    X = repeat(x', length(y), 1)
    Y = repeat(y, 1, length(x))
    # Evaluate each f(x, y)
    Z = map((x,y) -> f([x,y]), X, Y)
    plot(x, y, Z, st=:surface)
end
ezsurf(-3:0.1:3,-3:0.1:3,
  quadratic_ls(A,b))
plot!(colorbar=false,size=(500,450))
# Show the gradient at x = [1,1]
x = [-2,2]
g = A*x - b
g = 0.1.*g

plot!([x[1],x[1]+g[1]],[x[2],x[2]+g[2]],[quadratic_ls(A,b)(x), quadratic_ls(A,b)(x+g)],
  line=(arrow=:arrow),label="",color=2)
  plot!([x[1],x[1]-g[1]],[x[2],x[2]-g[2]],[quadratic_ls(A,b)(x), quadratic_ls(A,b)(x-g)],
    line=(arrow=:arrow),label="",color=3)
##
anim = @animate for i=1:360
  plot!(camera=(i,30))
end
gif(anim, "quadratic_ls1.gif")
##
using Printf
using LinearAlgebra
""" Run gradient descent to solve a linear system of equations.

This function assumes that A is symmetric positive definite. """
function gradient_descent_linsys(A,b;step=0.1, maxiter=10*size(A,1),tol=1e-6)
  x = zeros(size(A,1)) # start at 0
  for i=1:maxiter
    g = A*x - b
    @printf("iteration %4i  residual = %.3e\n", i, norm(g))
    if norm(g) <= tol
      break
    end
    x -= step*g
  end
  return x
end
gradient_descent_linsys(A,b)
## Animate the algorithm
ezsurf(-0.5:0.025:0.5,-0.5:0.025:0.5,
  quadratic_ls(A,b))
plot!(colorbar=false,size=(500,450))
plot!(camera=(170,30))
x = zeros(size(A,1)) # initialize
p = plot3d!(1, label="", marker = 2)
step = 0.1
anim = @animate for i=1:20
  global x
  g = A*x - b
  x -= step*g
  push!(p[1][2], x[1], x[2], quadratic_ls(A,b)(x))
  title!(@sprintf("Iteration %3i  Residual = %.3e", i, norm(g)))
end
gif(anim, "gradient_descent_ls1.gif")


text:
#Gram-Schmidt Orthogonalization

function normalized_orthogonal_projection(b,Z::AbstractArray)
    annihilator =  I - Z * inv(Z'*Z) *Z'
    projection = annihilator*b
    return projection / norm(projection)
end

function gram_schmidt(x::AbstractArray)

    U = similar(x,Float64)

    for col in 1:size(U,2)
        b = X[:,col]       # vector we're going to project
        Z = X[:,1:col - 1] # first i-1 columns of X
        U[:,col] = normalized_orthogonal_projection(b, Z)
   end
   return U
end

y = [1, 3, -3]
X = [1 0; 0 -6; 2 2];

Py1 = X * inv(X'X) * X' * y #ordinary projection

U = gram_schmidt(X) #construct orthogonal set

Py2 = U*U'*y #use orthonormal projection result

#perform the same projection using QR decomposition
Q, R = qr(X)
Q = Matrix(Q)
R = Matrix(R)

Py3 = Q*Q'*y # Q is formed of columns from orthonormal basis of x
beta = inv(R)*Q'*y

max_stars_repo_name: shanemcmiken/quantecon-notebooks-julia

max_issues_repo_name: shanemcmiken/quantecon-notebooks-julia

max_forks_repo_name: shanemcmiken/quantecon-notebooks-julia


text:
## Exercise 6-8
## The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.

## One way to find the GCD of two numbers is based on the observation that if r is the remainder when a is divided by b, then gcd(a, b) = gcd(b, r). As a base case, we can use gcd(a, 0) = a.

## Write a function called gcd that takes parameters a and b and returns their greatest common divisor.
println("Ans: ")

function gcd(a, b)
    remainder = a % b
    if remainder == 0
        return b
    end
    return gcd(b, remainder)
end

println(gcd(210, 55))
println(gcd(12576, 4052))
println(gcd(4, 3))

println("End.")


text:
# ------------------------------------------------------------------------------------------
# ## How can we calculate $\pi$?
#
# Given a square of length $2r$, the square's area is
#
# $$A_{square} = (2r)^2 = 4r^2$$
#
# whereas the area of a circle with radius $r$ is
# $$A_{circle} = \pi r^2$$
#
#
#
# Therefore the ratio of the area of the circle to that of the square above is
#
# $$\frac{A_{circle}}{A_{square}} = \frac{\pi r^2}{4r^2} = \frac{\pi}{4}$$
#
# and we can define $\pi$ as
#
# $$\pi = 4\frac{A_{circle}}{A_{square}}$$
#
# This suggests a way to calculate $\pi$: if we have a square and the largest circle that
# fits inside that square, we can determine the ratio of areas of a circle and a square. We
# can calculate this ratio using a monte carlo simulation. We select random points inside a
# square, and we keep track of how often those points also fall inside the circle that fits
# perfectly inside that square.
#
# Given a large enough sampling points, $\frac{A_{circle}}{A_{square}}$ will be equal to the
# fraction of randomly chosen points inside the square that also fall inside the circle.
# Then we can figure out $\pi$!
#
# #### Pseudo-code
#
# Given the above, our algorithm for determining $\pi$ looks like this:
#
# 1. For each of $N$ iterations,
#     1. Select a random point inside a square of area $4r^2$ as Cartesian, $(x, y)$,
# coordinates.
#     1. Determine if the point also falls inside the circle embedded within this square of
# area $\pi r^2$.
#     1. Keep track of whether or not this point fell inside the circle. At the end of $N$
# iterations, you want to know $M$ -- the number of the $N$ random points that fell inside
# the circle!
# 1. Calculate $\pi$ as $4\frac{M}{N}$
#
# #### Exercise
#
# Write a function that calculates $\pi$ using Julia.
#
# The algorithm above should work for any value of $r$ that you choose to use. Make sure you
# make $N$ big enough that the value of $\pi$ is correct to at least a couple numbers after
# the decimal point!
#
# *Hint*:
#
# This will probably be easier if you center your circle and square at the coordinate (0, 0)
# and use a radius of 1. For example, to choose random coordinates within your square at
# position (x, y), you may want to choose x and y so that they are each a value between -1
# and +1. Then any point within a distance of 1 from (0, 0) will fall inside the circle!
#
#
#
#
# ------------------------------------------------------------------------------------------

max_stars_repo_name: grenkoca/JuliaTutorials

max_issues_repo_name: grenkoca/JuliaTutorials

max_forks_repo_name: grenkoca/JuliaTutorials