Skip to content
This repository was archived by the owner on Oct 10, 2022. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Algebra-and-Numerical-Methods/GCD.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Name : GCD of two numbers in log(max(a,b)) time.
// Time Complexity : log(max(a,b));
// Space Complexity : constant

#include <bits/stdc++.h>
#define int long long
using namespace std;

int gcd(int a, int b) {
// use the result that gcd(a,b) = gcd(b%a,a) recursively;
if(b == 0) return a;
if(a == 0) return b;
return gcd(b%a,a);
}

signed main()
{
int a, b;
// Enter the 2 numbers to calculate the gcd;
cin>>a>>b;
cout<<gcd(a,b);
return 0;
}
69 changes: 69 additions & 0 deletions Data-Structures/Segment_Tree_Template.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Name : Segment tree for range sum queries and point updates.
// Time complexity : build : nlogn
// query : logn
// update : logn
// Space Complexity : n

struct segtree {
vector<int> arr;
int sz = 1;
void init(int n) {
while(sz < n) sz *= 2;
arr.assign(2*sz,0);
}
void update(int pos, int val, int curr_node, int l, int r) {
if(r-l == 1) {
// here the curr_node will become = to i;


arr[curr_node] = val;
return;
}
// now decide where to go - left subtree or right subtree


int m = (l+r)/2;
if(pos < m) {
// go left

update(pos,val,2*curr_node+1,l,m);

// curr_node becomes the left child of x i.e 2*x+1;
} else {
// go right

update(pos,val,2*curr_node+2,m,r);

// curr_node becomes the right child of x i.e 2*x+2;
}
// and here the sum of curr_node = sum of left child and right child


arr[curr_node] = arr[2*curr_node+1]+arr[2*curr_node+2];
return;
}

void update(int pos, int val) {
update(pos,val,0,0,sz);


// 0 means the root; we start update with the root
}

/*------------
this is where all the changes will be made for point updates;
-------------*/


int sum(int l, int r, int curr_node, int currL, int currR) {
if(currL >= r || currR <= l) return 0; // outside the segment
if(currL >= l && currR <= r) return arr[curr_node]; // totally inside the segment
int m = (currL+currR)/2;
int ans = sum(l,r,2*curr_node+1,currL,m) + sum(l,r,2*curr_node+2,m,currR);
return ans;
}

int sum(int l, int r) {
return sum(l,r,0,0,sz);
}
};