Upload basic README.md

This commit is contained in:
Michael Reber 2019-11-18 14:44:36 +01:00
parent 8258e10e80
commit f4fa9cdf8e
867 changed files with 35571 additions and 0 deletions

3
assembly/README.md Normal file
View File

@ -0,0 +1,3 @@
# Assembly language
An assembly language is an extremely low-level programming language that has a 1-to-1 correspondence to machine code — the series of binary instructions which move values in and out of registers in a CPU (or other microprocessor)

43
c++/Basic/2D Array.cpp Normal file
View File

@ -0,0 +1,43 @@
#include <iostream>
#define size 16
using namespace std;
int main ()
{
int m,n;
int a[size][size];
cout<<"Enter the number of rows"<<endl;
cin>>m;
cout<<"Enter the number of columns"<<endl;
cin>>n;
cout<<"Enter the Elements in Table"<<endl;
for ( int i = 0; i < m; i++ )
{
for ( int j = 0; j < n; j++ )
{
cin >>a[i][j];
}
}
// output each array element"s value
for ( int i = 0; i < m; i++ )
for ( int j = 0; j < n; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
Output:
Enter the number of rows
2
Enter the number of columns
3
Enter the Elements in Table
1 2 3 4 5 6
a[0][0]: 1
a[0][1]: 2
a[0][2]: 3
a[1][0]: 4
a[1][1]: 5
a[1][2]: 6

View File

@ -0,0 +1,17 @@
#include < iostream.h >
int main()
{
int n, sum = 0, c, value;
cout<<"Enter the number of integers you want to add\n";
cin>>n;
cout<<"Enter"<<n<<"integers"<<"\n";
for (c = 1; c <= n; c++)
{
cin>>value;
sum = sum + value;
/*adding each no in sum*/
}
cout<<"Sum of entered integers ="<<sum<<"\n";
return 0;
}

View File

@ -0,0 +1,19 @@
#include < iostream.h >
int main()
{
int first, second, add, subtract, multiply;
float divide;
cout<<"Enter two integers\n";
cin>>first>>second;
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / (float)second;
//typecasting
cout<<"Sum = "<<add<<"\n";
cout<<"Difference ="<<subtract<<"\n";
cout<<"Multiplication ="<<multiply<<"\n";
cout<<"Division ="<<divide<<"\n";
return 0;
}

View File

@ -0,0 +1,17 @@
#include <iostream>
int main()
{
int n, sum = 0, remainder;
cout<<"Enter an integer\n";
cin>>n;
while(n != 0)
{
remainder = n % 10;
/*stores unit place digit to remainder*/
sum = sum + remainder;
n = n / 10;
/*dividing no to discard unit place digit*/
}
cout<<"Sum of digits of entered number = "<<sum<<endl;
return 0;
}

View File

@ -0,0 +1,28 @@
#include < iostream.h >
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
cout<<"Enter the number of rows and columns of matrix\n";
cin>>m>>n;
cout<<"Enter the elements of first matrix\n";
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
cin>>first[c][d];
cout<<"Enter the elements of second matrix\n";
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
cin>>second[c][d];
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d];
/* Matrix addition */
cout<<"Sum of entered matrices:-\n";
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
cout<<sum[c][d]<<"\t";
cout<<"\n";
}
return 0;
}

View File

@ -0,0 +1,12 @@
#include < iostream.h >
void main()
{
int height, base;
float ans;/*ans may come in fractions*/
cout<<"Enter height and base";
cin>>height>>base;
ans= (1/2)*height*base;
/* mathematical formula*/
cout<<"Area if triangle is"<<ans;
}

82
c++/Basic/BellmanFord.cpp Normal file
View File

@ -0,0 +1,82 @@
#include <vector>
#include <climits>
#include <iostream>
using namespace std;
typedef pair<int, int> pii;
typedef vector<vector<pii> > Graph;
const int INF = INT_MAX / 3;
bool bellmanFord(Graph &g, int s, vector<int> &prio, vector<int> &pred) {
int n = g.size();
pred.assign(n, -1);
prio.assign(n, INF);
prio[s] = 0;
bool wasChanged = true;
for (int k = 0; k < n; k++) {
wasChanged = false;
for (int u = 0; u < n; u++) {
for (int i = 0; i < (int) g[u].size(); i++) {
int v = g[u][i].first;
int cost = g[u][i].second;
if (prio[v] > prio[u] + cost) {
prio[v] = prio[u] + cost;
pred[v] = u;
wasChanged = true;
}
}
}
if (!wasChanged)
break;
}
// wasChanged is true iff graph has a negative cycle
return wasChanged;
}
vector<int> findNegativeCycle(Graph &g) {
int n = g.size();
vector<int> pred(n, -1);
vector<int> prio(n, INF);
prio[0] = 0;
int last = 0;
for (int k = 0; k < n; k++) {
last = -1;
for (int u = 0; u < n; u++) {
for (int i = 0; i < (int) g[u].size(); i++) {
int v = g[u][i].first;
int cost = g[u][i].second;
if (prio[v] > prio[u] + cost) {
prio[v] = prio[u] + cost;
pred[v] = u;
last = v;
}
}
}
if (last == -1)
return vector<int>();
}
vector<int> path(n);
vector<int> pos(n, -1);
for (int i = 0;; i++) {
if (pos[last] != -1)
return vector<int>(path.rend() - i, path.rend() - pos[last]);
path[i] = last;
pos[last] = i;
last = pred[last];
}
}
int main() {
Graph g(4);
g[0].push_back(make_pair(1, 1));
g[1].push_back(make_pair(0, 1));
g[1].push_back(make_pair(2, 1));
g[2].push_back(make_pair(3, -10));
g[3].push_back(make_pair(1, 1));
vector<int> cycle = findNegativeCycle(g);
for (int i = 0; i < (int) cycle.size(); i++)
cout << cycle[i] << " ";
}

View File

@ -0,0 +1,73 @@
#include < iostream.h >
using namespace std;
class Cube
{
public:
void setLength( double l )
{
length = l;
}
void setBreadth( double b )
{
breadth = b;
}
void setHeight( double h )
{
height = h;
}
double getVolume(void)
{
return length * breadth * height;
}
// Overload + operator to add two Cube objects.
Cube operator+(const Cube& b)
{
Cube C;
C.length = this->length + b.length;
C.breadth = this->breadth + b.breadth;
C.height = this->height + b.height;
return C;
}
private:
double length; // Length of a Cube
double breadth; // Breadth of a Cube
double height; // Height of a Cube
};
// Main function for the program
int main( )
{
Cube C1; // Declare C1 of type Cube
Cube C2; // Declare C2 of type Cube
Cube C3; // Declare C3 of type Cube
double volume = 0.0; // Store the volume of a Cube here
// Cube 1 specification
C1.setLength(4.0);
C1.setBreadth(6.0);
C1.setHeight(5.0);
// Cube 2 specification
C2.setLength(8.0);
C2.setBreadth(4.0);
C2.setHeight(10.0);
// volume of Cube 1
volume = C1.getVolume();
cout << "Volume of Cube 1 : " << volume <<endl;
// volume of Cube 2
volume = C2.getVolume();
cout << "Volume of Cube 2 : " << volume <<endl;
// Add two object as follows:
C3 = C1 + C2;
// volume of Cube 3
volume = C3.getVolume();
cout << "Volume of Cube 3 : " << volume <<endl;
return 0;
}
Output
Volume of Cube 1 : 120
Volume of Cube 2 : 320
Volume of Cube 3 : 1800

View File

@ -0,0 +1,50 @@
#include < iostream.h >
int main()
{
int a[10],i,n,m,c,l,u;
cout<<"Enter the size of an array: ";
cin>>n;
cout<<"Enter the elements of the array: " ;
for(i=0; i < n; i++)
cin>>a[i];
cout<<"Enter the number to be search: ";
cin>>m;
l=0,u=n-1;
c=binary(a,n,m,l,u);
if(c==0)
cout<<"Number is not found.";
else
cout<<"Number is found.";
return 0;
}
/*Binary search will search element at middle, if element is not found and if element to be searched is less than middle then it will search only in lower part and if greater then in upper part */
int binary(int a[],int n,int m,int l,int u)
{
int mid,c=0;
if(l < = u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
}
else if(m < a[mid])
{
return binary(a,n,m,l,mid-1);
}
else
return binary(a,n,m,mid+1,u);
}
else
return c;
}
Output:
Enter the size of an array:4
Enter the elements of the array:5 3 6 2
Enter the number to be search:3
Number is found.
Number is found.

View File

@ -0,0 +1,19 @@
#include < iostream.h >
void main()
{
int num, binary_val, decimal_val = 0, base = 1, rem;
cout<<"Enter a binary number(1s and 0s) \n";
cin>>amp num;
binary_val = num;
while (num > 0)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
num = num / 10 ;
num = num / 10 ;
base = base * 2;
}
cout<<"The Binary number is ="<<binary_val<<" \n";
cout<<"Its decimal equivalent is ="<<decimal_val<<" \n";
}

View File

@ -0,0 +1,17 @@
#include < iostream.h>
int main()
{
long int binaryval, hexadecimalval = 0, i = 1, remainder;
cout<<"Enter the binary number: ";
cin>>binaryval;
while (binaryval != 0)
{
remainder = binaryval % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
cout<<"Equivalent hexadecimal value:"<<hexadecimalval;
return 0;
}

View File

@ -0,0 +1,17 @@
#include < iostream.h>
int main()
{
long int binarynum, octalnum = 0, j = 1, remainder;
cout<<"Enter the value for binary number: ";
cin>>binarynum;
while (binarynum != 0)
{
remainder = binarynum % 10;
octalnum = octalnum + remainder * j;
j = j * 2;
binarynum = binarynum / 10;
}
cout<<"Equivalent octal value:"<<octalnum;
return 0;
}

20
c++/Basic/BinaryPow.cpp Normal file
View File

@ -0,0 +1,20 @@
#include <iostream>
using namespace std;
int pow(int x, int n, int MOD) {
long long y = x;
int res = 1;
for (; n > 0; n >>= 1) {
if (n & 1)
res = res * y % MOD;
y = y * y % MOD;
}
return res;
}
int main() {
const int MOD = 1000000007;
int x = pow(2, 10, MOD);
cout << x << endl;
}

View File

@ -0,0 +1,20 @@
#include <iostream.h>
#include<conio.h>
void main()
{
clrscr(); //clear screen
int number;
cout<< "Enter an integer: ";
cin>> number;
if ( number >= 0)
{
cout << "You entered a positive integer: "<<number<<endl;
}
else
{
cout<<"You entered a negative integer: "<<number<<endl;
}
cout<<"This statement is always executed because it's outside if...else statement.";
getch();
}

37
c++/Basic/Comparator.cpp Normal file
View File

@ -0,0 +1,37 @@
#include <algorithm>
#include <set>
#include <iostream>
using namespace std;
struct item {
int x, y;
bool operator<(const item &o) const {
return x < o.x || x == o.x && y < o.y;
}
};
struct item_cmp {
bool operator()(const item &a, const item &b) {
return a.x < b.x || a.x == b.x && a.y < b.y;
}
};
bool cmp(const item &a, const item &b) {
return a.x < b.x || a.x == b.x && a.y < b.y;
}
int main() {
item a[] = { { 2, 3 }, { 1, 2 } };
//typedef set<item, bool(*)(const item&, const item&)> myset;
//myset s(a, a + 2, cmp);
//typedef set<item, item_cmp> myset;
typedef set<item> myset;
myset s(a, a + 2);
for (myset::iterator it = s.begin(); it != s.end(); it++) {
cout << it->x << " " << it->y << endl;
}
sort(a, a + 2, cmp);
sort(a, a + 2, item_cmp());
cout << a[0].x << " " << a[0].y << endl;
}

39
c++/Basic/ConvexHull.cpp Normal file
View File

@ -0,0 +1,39 @@
#include <algorithm>
#include <iostream>
using namespace std;
typedef pair<long long, long long> point;
long long cross(const point &a, const point &b, const point &c) {
return (b.first - a.first) * (c.second - a.second) - (b.second - a.second) * (c.first - a.first);
}
vector<point> convexHull(vector<point> points) {
if (points.size() <= 1)
return points;
sort(points.begin(), points.end());
vector<point> h;
for (auto p: points) {
while (h.size() >= 2 && cross(h.end()[-2], h.back(), p) >= 0)
h.pop_back();
h.push_back(p);
}
reverse(points.begin(), points.end());
int upper = h.size();
for (auto p: points) {
while (h.size() > upper && cross(h.end()[-2], h.back(), p) >= 0)
h.pop_back();
h.push_back(p);
}
h.resize(h.size() - 1 - (h[0] == h[1]));
return h;
}
// Usage example
int main() {
vector<point> hull1 = convexHull((vector<point>) {point(0, 0), point(3, 0), point(0, 3), point(1, 1)});
cout << (3 == hull1.size()) << endl;
vector<point> hull2 = convexHull((vector<point>) {point(0, 0), point(0, 0)});
cout << (1 == hull2.size()) << endl;
}

View File

@ -0,0 +1,14 @@
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
cout << "Current Date is : "
cout << now->tm_mday << '-'<< (now->tm_mon + 1) << '-' << (now->tm_year + 1900) << endl;
}
Output
Current Date is : 16-6-2015

View File

@ -0,0 +1,19 @@
#include < iostream.h >
int main()
{
int n, c, k;
cout<<"Enter an integer in decimal number system\n";
cin>>n;
cout<<n<<"in binary number system is:\n";
for (c = 31; c >= 0; c--)
{
k = n >> c;
/*Right shift(Binary Divide by 2)*/
if (k & 1)//k is logically ANDed with 1
cout<<"1";
else
cout<<"0";
}
return 0;
}

View File

@ -0,0 +1,18 @@
#include <iostream.h>
void main()
{
long num, decimal_num, remainder, base = 1, octal = 0;
cout<<"Enter a decimal integer \n";
cin>>amp num;
decimal_num = num;
while (num > 0)
{
remainder = num % 8;
octal = octal + remainder * base;
num = num / 8;
base = base * 10;
}
cout<<"Input number is ="<<decimal_num<<"\n";
cout<<"Its octal equivalent is ="<<Octal<<"\n";
}

View File

@ -0,0 +1,47 @@
#include < iostream.h >
#include < string.h >
int check_vowel(char);
int main()
{
char s[100], t[100];
int i, j = 0;
cout<<"Enter a string to delete vowels\n";
gets(s);
/* In the program we create a new string and process entered string character by character, and if a vowel is found it is not added to new string otherwise the character is added to new string, after the string ends we copy the new string into original string*/
for(i = 0; s[i] != '\0'; i++)
{
if(check_vowel(s[i]) == 0)
{
/* not a vowel */
t[j] = s[i];
j++
;
}
}
t[j] = '\0';
strcpy(s, t);
/* We are changing initial string */
cout<<"String after deleting vowels:"<< s<<"\n";
return 0;
}
int check_vowel(char c)
{
switch(c)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1;
default:
return 0;
}
}

67
c++/Basic/Diameter.cpp Normal file
View File

@ -0,0 +1,67 @@
#include <algorithm>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
typedef pair<double, double> point;
bool cw(const point &a, const point &b, const point &c) {
return (b.first - a.first) * (c.second - a.second) - (b.second - a.second) * (c.first - a.first) < 0;
}
vector<point> convexHull(vector<point> p) {
int n = p.size();
if (n <= 1)
return p;
int k = 0;
sort(p.begin(), p.end());
vector<point> q(n * 2);
for (int i = 0; i < n; q[k++] = p[i++])
for (; k >= 2 && !cw(q[k - 2], q[k - 1], p[i]); --k)
;
for (int i = n - 2, t = k; i >= 0; q[k++] = p[i--])
for (; k > t && !cw(q[k - 2], q[k - 1], p[i]); --k)
;
q.resize(k - 1 - (q[0] == q[1]));
return q;
}
double area(const point &a, const point &b, const point &c) {
return abs((b.first - a.first) * (c.second - a.second) - (b.second - a.second) * (c.first - a.first));
}
double dist(const point &a, const point &b) {
return hypot(a.first - b.first, a.second - b.second);
}
double diameter(const vector<point> &p) {
vector<point> h = convexHull(p);
int m = h.size();
if (m == 1)
return 0;
if (m == 2)
return dist(h[0], h[1]);
int k = 1;
while (area(h[m - 1], h[0], h[(k + 1) % m]) > area(h[m - 1], h[0], h[k]))
++k;
double res = 0;
for (int i = 0, j = k; i <= k && j < m; i++) {
res = max(res, dist(h[i], h[j]));
while (j < m && area(h[i], h[(i + 1) % m], h[(j + 1) % m]) > area(h[i], h[(i + 1) % m], h[j])) {
res = max(res, dist(h[i], h[(j + 1) % m]));
++j;
}
}
return res;
}
int main() {
vector<point> points(4);
points[0] = point(0, 0);
points[1] = point(3, 0);
points[2] = point(0, 3);
points[3] = point(1, 1);
double d = diameter(points);
cout << d << endl;
}

73
c++/Basic/Dijkstra.cpp Normal file
View File

@ -0,0 +1,73 @@
#include <vector>
#include <queue>
#include <set>
#include <climits>
#include <iostream>
using namespace std;
typedef pair<int, int> pii;
typedef vector<vector<pii> > Graph;
void dijkstra(Graph &g, int s, vector<int> &prio, vector<int> &pred) {
int n = g.size();
prio.assign(n, INT_MAX);
prio[s] = 0;
pred.assign(n, -1);
priority_queue<pii, vector<pii> , greater<pii> > q;
q.push(make_pair(prio[s], s));
while (!q.empty()) {
int d = q.top().first;
int u = q.top().second;
q.pop();
if (d != prio[u])
continue;
for (int i = 0; i < (int) g[u].size(); i++) {
int v = g[u][i].first;
int nprio = prio[u] + g[u][i].second;
if (prio[v] > nprio) {
prio[v] = nprio;
pred[v] = u;
q.push(make_pair(nprio, v));
}
}
}
}
void dijkstra2(Graph &g, int s, vector<int> &prio, vector<int> &pred) {
int n = g.size();
prio.assign(n, INT_MAX);
prio[s] = 0;
pred.assign(n, -1);
set<pii> q;
q.insert(make_pair(prio[s], s));
while (!q.empty()) {
int u = q.begin()->second;
q.erase(q.begin());
for (int i = 0; i < (int) g[u].size(); ++i) {
int v = g[u][i].first;
int nprio = prio[u] + g[u][i].second;
if (prio[v] > nprio) {
q.erase(make_pair(prio[v], v));
prio[v] = nprio;
pred[v] = u;
q.insert(make_pair(prio[v], v));
}
}
}
}
int main() {
Graph g(3);
g[0].push_back(make_pair(1, 10));
g[1].push_back(make_pair(2, -5));
g[0].push_back(make_pair(2, 8));
vector<int> prio;
vector<int> pred;
dijkstra(g, 0, prio, pred);
for (int i = 0; i < prio.size(); i++)
cout << prio[i] << endl;
}

123
c++/Basic/DijkstraHeap.cpp Normal file
View File

@ -0,0 +1,123 @@
#include <algorithm>
#include <climits>
#include <iostream>
using namespace std;
const int maxnodes = 200000;
const int maxedges = 1000000;
// graph
int edges;
int last[maxnodes], head[maxedges], previous[maxedges], len[maxedges];
int prio[maxnodes], pred[maxnodes];
void graphClear() {
fill(last, last + maxnodes, -1);
edges = 0;
}
void addEdge(int u, int v, int length) {
head[edges] = v;
len[edges] = length;
previous[edges] = last[u];
last[u] = edges++;
}
// heap
int h[maxnodes];
int pos2Id[maxnodes];
int id2Pos[maxnodes];
int hsize;
void hswap(int i, int j) {
swap(h[i], h[j]);
swap(pos2Id[i], pos2Id[j]);
swap(id2Pos[pos2Id[i]], id2Pos[pos2Id[j]]);
}
void moveUp(int pos) {
while (pos > 0) {
int parent = (pos - 1) >> 1;
if (h[pos] >= h[parent]) {
break;
}
hswap(pos, parent);
pos = parent;
}
}
void add(int id, int prio) {
h[hsize] = prio;
pos2Id[hsize] = id;
id2Pos[id] = hsize;
moveUp(hsize++);
}
void increasePriority(int id, int prio) {
int pos = id2Pos[id];
h[pos] = prio;
moveUp(pos);
}
void moveDown(int pos) {
while (pos < (hsize >> 1)) {
int child = 2 * pos + 1;
if (child + 1 < hsize && h[child + 1] < h[child]) {
++child;
}
if (h[pos] <= h[child]) {
break;
}
hswap(pos, child);
pos = child;
}
}
int removeMin() {
int res = pos2Id[0];
int lastNode = h[--hsize];
if (hsize > 0) {
h[0] = lastNode;
int id = pos2Id[hsize];
id2Pos[id] = 0;
pos2Id[0] = id;
moveDown(0);
}
return res;
}
void dijkstra(int s) {
fill(pred, pred + maxnodes, -1);
fill(prio, prio + maxnodes, INT_MAX);
prio[s] = 0;
hsize = 0;
add(s, prio[s]);
while (hsize) {
int u = removeMin();
for (int e = last[u]; e >= 0; e = previous[e]) {
int v = head[e];
int nprio = prio[u] + len[e];
if (prio[v] > nprio) {
if (prio[v] == INT_MAX)
add(v, nprio);
else
increasePriority(v, nprio);
prio[v] = nprio;
pred[v] = u;
}
}
}
}
int main() {
graphClear();
addEdge(0, 1, 10);
addEdge(1, 2, -5);
addEdge(0, 2, 8);
dijkstra(0);
for (int i = 0; i < 3; i++)
cout << prio[i] << endl;
}

View File

@ -0,0 +1,36 @@
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 200000;
int Rank[maxn];
int p[maxn];
int n;
void init(int n) {
::n = n;
fill(Rank, Rank + n, 0);
for (int i = 0; i < n; i++) p[i] = i;
}
int root(int x) {
return x == p[x] ? x : (p[x] = root(p[x]));
}
void unite(int a, int b) {
a = root(a);
b = root(b);
if (a == b) return;
if (Rank[a] < Rank[b]) swap(a, b);
if (Rank[a] == Rank[b]) ++Rank[a];
p[b] = a;
}
int main() {
init(3);
unite(0, 2);
cout << (0 == root(0)) << endl;
cout << (1 == root(1)) << endl;
cout << (0 == root(2)) << endl;
}

137
c++/Basic/FFT.cpp Normal file
View File

@ -0,0 +1,137 @@
// https://web.stanford.edu/~liszt90/acm/notebook.html#file16
// Fast Fourier Transform : Used in many applications(one is fast polynomial multiplication)
#include <cassert>
#include <cstdio>
#include <cmath>
struct cpx
{
cpx(){}
cpx(double aa):a(aa),b(0){}
cpx(double aa, double bb):a(aa),b(bb){}
double a;
double b;
double modsq(void) const
{
return a * a + b * b;
}
cpx bar(void) const
{
return cpx(a, -b);
}
};
cpx operator +(cpx a, cpx b)
{
return cpx(a.a + b.a, a.b + b.b);
}
cpx operator *(cpx a, cpx b)
{
return cpx(a.a * b.a - a.b * b.b, a.a * b.b + a.b * b.a);
}
cpx operator /(cpx a, cpx b)
{
cpx r = a * b.bar();
return cpx(r.a / b.modsq(), r.b / b.modsq());
}
cpx EXP(double theta)
{
return cpx(cos(theta),sin(theta));
}
const double two_pi = 4 * acos(0);
// in: input array
// out: output array
// step: {SET TO 1} (used internally)
// size: length of the input/output {MUST BE A POWER OF 2}
// dir: either plus or minus one (direction of the FFT)
// RESULT: out[k] = \sum_{j=0}^{size - 1} in[j] * exp(dir * 2pi * i * j * k / size)
void FFT(cpx *in, cpx *out, int step, int size, int dir)
{
if(size < 1) return;
if(size == 1)
{
out[0] = in[0];
return;
}
FFT(in, out, step * 2, size / 2, dir);
FFT(in + step, out + size / 2, step * 2, size / 2, dir);
for(int i = 0 ; i < size / 2 ; i++)
{
cpx even = out[i];
cpx odd = out[i + size / 2];
out[i] = even + EXP(dir * two_pi * i / size) * odd;
out[i + size / 2] = even + EXP(dir * two_pi * (i + size / 2) / size) * odd;
}
}
// Usage:
// f[0...N-1] and g[0..N-1] are numbers
// Want to compute the convolution h, defined by
// h[n] = sum of f[k]g[n-k] (k = 0, ..., N-1).
// Here, the index is cyclic; f[-1] = f[N-1], f[-2] = f[N-2], etc.
// Let F[0...N-1] be FFT(f), and similarly, define G and H.
// The convolution theorem says H[n] = F[n]G[n] (element-wise product).
// To compute h[] in O(N log N) time, do the following:
// 1. Compute F and G (pass dir = 1 as the argument).
// 2. Get H by element-wise multiplying F and G.
// 3. Get h by taking the inverse FFT (use dir = -1 as the argument)
// and *dividing by N*. DO NOT FORGET THIS SCALING FACTOR.
int main(void)
{
printf("If rows come in identical pairs, then everything works.\n");
cpx a[8] = {0, 1, cpx(1,3), cpx(0,5), 1, 0, 2, 0};
cpx b[8] = {1, cpx(0,-2), cpx(0,1), 3, -1, -3, 1, -2};
cpx A[8];
cpx B[8];
FFT(a, A, 1, 8, 1);
FFT(b, B, 1, 8, 1);
for(int i = 0 ; i < 8 ; i++)
{
printf("%7.2lf%7.2lf", A[i].a, A[i].b);
}
printf("\n");
for(int i = 0 ; i < 8 ; i++)
{
cpx Ai(0,0);
for(int j = 0 ; j < 8 ; j++)
{
Ai = Ai + a[j] * EXP(j * i * two_pi / 8);
}
printf("%7.2lf%7.2lf", Ai.a, Ai.b);
}
printf("\n");
cpx AB[8];
for(int i = 0 ; i < 8 ; i++)
AB[i] = A[i] * B[i];
cpx aconvb[8];
FFT(AB, aconvb, 1, 8, -1);
for(int i = 0 ; i < 8 ; i++)
aconvb[i] = aconvb[i] / 8;
for(int i = 0 ; i < 8 ; i++)
{
printf("%7.2lf%7.2lf", aconvb[i].a, aconvb[i].b);
}
printf("\n");
for(int i = 0 ; i < 8 ; i++)
{
cpx aconvbi(0,0);
for(int j = 0 ; j < 8 ; j++)
{
aconvbi = aconvbi + a[j] * b[(8 + i - j) % 8];
}
printf("%7.2lf%7.2lf", aconvbi.a, aconvbi.b);
}
printf("\n");
return 0;
}

47
c++/Basic/FenwickTree.cpp Normal file
View File

@ -0,0 +1,47 @@
#include <iostream>
using namespace std;
const int maxn = 200000;
int t[maxn];
void add(int t[], int i, int value) {
for (; i < maxn; i |= i + 1)
t[i] += value;
}
// sum[0,i]
int sum(int t[], int i) {
int res = 0;
for (; i >= 0; i = (i & (i + 1)) - 1)
res += t[i];
return res;
}
// Returns min(p|sum[0,p]>=sum)
int lower_bound(int t[], int sum) {
--sum;
int pos = -1;
for (int blockSize = 1 << 30; blockSize != 0; blockSize >>= 1) {
if (blockSize > maxn) continue;
int nextPos = pos + blockSize;
if (nextPos < maxn && sum >= t[nextPos]) {
sum -= t[nextPos];
pos = nextPos;
}
}
return pos + 1;
}
// Usage example
int main() {
add(t, 0, 4);
add(t, 1, 5);
add(t, 2, 5);
add(t, 2, 5);
cout << (4 == sum(t, 0)) << endl;
cout << (19 == sum(t, 2)) << endl;
cout << (2 == lower_bound(t, 19)) << endl;
cout << (maxn == lower_bound(t, 20)) << endl;
}

View File

@ -0,0 +1,31 @@
#include <iostream>
#include <map>
using namespace std;
const int n = 2000000000;
void add(map<int, int> &t, int i, int value) {
for (; i < n; i |= i + 1)
t[i] += value;
}
// sum[0,i]
int sum(map<int, int> &t, int i) {
int res = 0;
for (; i >= 0; i = (i & (i + 1)) - 1)
if (t.count(i)) res += t[i];
return res;
}
// Usage example
int main() {
map<int, int> t;
add(t, 0, 4);
add(t, 1, 5);
add(t, 2, 5);
add(t, 2, 5);
cout << (4 == sum(t, 0)) << endl;
cout << (19 == sum(t, 2)) << endl;
cout << (19 == sum(t, 1000000000)) << endl;
}

View File

@ -0,0 +1,12 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
getch();
}

View File

@ -0,0 +1,103 @@
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
typedef pair<int, int> pii;
int cross(int ax, int ay, int bx, int by, int cx, int cy) {
return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
}
int cross(pii a, pii b, pii c) {
return cross(a.first, a.second, b.first, b.second, c.first, c.second);
}
class segment {
public:
pii a, b;
int id;
segment(pii a, pii b, int id) :
a(a), b(b), id(id) {
}
bool operator<(const segment &o) const {
if (a.first < o.a.first) {
int s = cross(a, b, o.a);
return (s > 0 || s == 0 && a.second < o.a.second);
} else if (a.first > o.a.first) {
int s = cross(o.a, o.b, a);
return (s < 0 || s == 0 && a.second < o.a.second);
}
return a.second < o.a.second;
}
};
class event {
public:
pii p;
int id;
int type;
event(pii p, int id, int type) :
p(p), id(id), type(type) {
}
bool operator<(const event &o) const {
return p.first < o.p.first || p.first == o.p.first && (type > o.type || type == o.type && p.second < o.p.second);
}
};
bool intersect(segment s1, segment s2) {
int x1 = s1.a.first, y1 = s1.a.second, x2 = s1.b.first, y2 = s1.b.second;
int x3 = s2.a.first, y3 = s2.a.second, x4 = s2.b.first, y4 = s2.b.second;
if (max(x1, x2) < min(x3, x4) || max(x3, x4) < min(x1, x2) || max(y1, y2) < min(y3, y4) || max(y3, y4) < min(y1, y2)) {
return false;
}
int z1 = (x3 - x1) * (y2 - y1) - (y3 - y1) * (x2 - x1);
int z2 = (x4 - x1) * (y2 - y1) - (y4 - y1) * (x2 - x1);
if (z1 < 0 && z2 < 0 || z1 > 0 && z2 > 0) {
return false;
}
int z3 = (x1 - x3) * (y4 - y3) - (y1 - y3) * (x4 - x3);
int z4 = (x2 - x3) * (y4 - y3) - (y2 - y3) * (x4 - x3);
if (z3 < 0 && z4 < 0 || z3 > 0 && z4 > 0) {
return false;
}
return true;
}
pii findIntersection(vector<segment> s) {
int n = s.size();
vector<event> e;
for (int i = 0; i < n; ++i) {
if (s[i].a > s[i].b)
swap(s[i].a, s[i].b);
e.push_back(event(s[i].a, i, 1));
e.push_back(event(s[i].b, i, -1));
}
sort(e.begin(), e.end());
set<segment> q;
for (int i = 0; i < n * 2; ++i) {
int id = e[i].id;
if (e[i].type == 1) {
set<segment>::iterator it = q.lower_bound(s[id]);
if (it != q.end() && intersect(*it, s[id]))
return make_pair(it->id, s[id].id);
if (it != q.begin() && intersect(*--it, s[id]))
return make_pair(it->id, s[id].id);
q.insert(s[id]);
} else {
set<segment>::iterator it = q.lower_bound(s[id]), next = it, prev = it;
if (it != q.begin() && it != --q.end()) {
++next, --prev;
if (intersect(*next, *prev))
return make_pair(next->id, prev->id);
}
q.erase(it);
}
}
return make_pair(-1, -1);
}
int main() {
}

View File

@ -0,0 +1,8 @@
#include<stdlib.h>
int main()
{
system("C:\\Windows\\System32\\ipconfig");
/* ipconfig command to get ip of system */
return 0;
}

36
c++/Basic/Hcf & Lcm.cpp Normal file
View File

@ -0,0 +1,36 @@
#include < iostream.h >
long gcd(long, long);
int main()
{
long x, y, hcf, lcm;
cout<<"Enter two integers\n";
cin>>x>>y;
hcf = gcd(x, y);
lcm = (x*y)/hcf;
cout<<"Greatest common divisor of "<<x <<"and"<<y<<" = "<<hcf<<"\n";
cout<<"Least common multiple of "<< x <<"and "<< y<<"= "<<lcm<<"\n";
return 0;
}
/*if 1st no is 0 then 2nd no is gcd
make 2nd no 0 by subtracting smallest from largest and return 1st no as gcd*/
long gcd(long x, long y)
{
if (x == 0)
{
return y;
}
while (y != 0)
{
if (x > y)
{
x = x - y;
}
else
{
y = y - x;
}
}
return x;
}

103
c++/Basic/KdTree.cpp Normal file
View File

@ -0,0 +1,103 @@
#include <algorithm>
#include <climits>
#include <vector>
#include <iostream>
using namespace std;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
const int maxn = 100000;
int tx[maxn];
int ty[maxn];
bool divX[maxn];
bool cmpX(const pii &a, const pii &b) {
return a.first < b.first;
}
bool cmpY(const pii &a, const pii &b) {
return a.second < b.second;
}
void buildTree(int left, int right, pii points[]) {
if (left >= right)
return;
int mid = (left + right) >> 1;
//sort(points + left, points + right + 1, divX ? cmpX : cmpY);
int minx = INT_MAX;
int maxx = INT_MIN;
int miny = INT_MAX;
int maxy = INT_MIN;
for (int i = left; i < right; i++) {
checkmin(minx, points[i].first);
checkmax(maxx, points[i].first);
checkmin(miny, points[i].second);
checkmax(maxy, points[i].second);
}
divX[mid] = (maxx - minx) >= (maxy - miny);
nth_element(points + left, points + mid, points + right, divX[mid] ? cmpX : cmpY);
tx[mid] = points[mid].first;
ty[mid] = points[mid].second;
if (left + 1 == right)
return;
buildTree(left, mid, points);
buildTree(mid + 1, right, points);
}
long long closestDist;
int closestNode;
void findNearestNeighbour(int left, int right, int x, int y) {
if (left >= right)
return;
int mid = (left + right) >> 1;
int dx = x - tx[mid];
int dy = y - ty[mid];
long long d = dx * (long long) dx + dy * (long long) dy;
if (closestDist > d && d) {
closestDist = d;
closestNode = mid;
}
if (left + 1 == right)
return;
int delta = divX[mid] ? dx : dy;
long long delta2 = delta * (long long) delta;
int l1 = left;
int r1 = mid;
int l2 = mid + 1;
int r2 = right;
if (delta > 0)
swap(l1, l2), swap(r1, r2);
findNearestNeighbour(l1, r1, x, y);
if (delta2 < closestDist)
findNearestNeighbour(l2, r2, x, y);
}
int findNearestNeighbour(int n, int x, int y) {
closestDist = LLONG_MAX;
findNearestNeighbour(0, n, x, y);
return closestNode;
}
int main() {
vpii p;
p.push_back(make_pair(0, 2));
p.push_back(make_pair(0, 3));
p.push_back(make_pair(-1, 0));
p.resize(unique(p.begin(), p.end()) - p.begin());
int n = p.size();
buildTree(1, 0, n - 1, &(vpii(p)[0]));
int res = findNearestNeighbour(n, 0, 0);
cout << p[res].first << " " << p[res].second << endl;
return 0;
}

65
c++/Basic/Manacher.cpp Normal file
View File

@ -0,0 +1,65 @@
// Linear Time algorithms for longestPalindrome in a string problem. It is one of the standard algorithms but is not very intuitive.
#include <vector>
#include <iostream>
#include <cstring>
using namespace std;
// Transform S into T.
// For example, S = "abba", T = "^#a#b#b#a#$".
// ^ and $ signs are sentinels appended to each end to avoid bounds checking
string preProcess(string s) {
int n = s.length();
if (n == 0) return "^$";
string ret = "^";
for (int i = 0; i < n; i++)
ret += "#" + s.substr(i, 1);
ret += "#$";
return ret;
}
string longestPalindrome(string s) {
string T = preProcess(s);
int n = T.length();
int *P = new int[n];
int C = 0, R = 0;
for (int i = 1; i < n-1; i++) {
int i_mirror = 2*C-i; // equals to i' = C - (i-C)
P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0;
// Attempt to expand palindrome centered at i
while (T[i + 1 + P[i]] == T[i - 1 - P[i]])
P[i]++;
// If palindrome centered at i expand past R,
// adjust center based on expanded palindrome.
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
// Find the maximum element in P.
int maxLen = 0;
int centerIndex = 0;
for (int i = 1; i < n-1; i++) {
if (P[i] > maxLen) {
maxLen = P[i];
centerIndex = i;
}
}
delete[] P;
return s.substr((centerIndex - 1 - maxLen)/2, maxLen);
}
int main() {
string text = "babcbabcbaccba";
std::cout << longestPalindrome(text)<< endl;
}

62
c++/Basic/Matrix.cpp Normal file
View File

@ -0,0 +1,62 @@
#include <vector>
#include <iostream>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
const int mod = 1234567891;
vvi matrixUnit(int n) {
vvi res(n, vi(n));
for (int i = 0; i < n; i++)
res[i][i] = 1;
return res;
}
vvi matrixAdd(const vvi &a, const vvi &b) {
int n = a.size();
int m = a[0].size();
vvi res(n, vi(m));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
res[i][j] = (a[i][j] + b[i][j]) % mod;
return res;
}
vvi matrixMul(const vvi &a, const vvi &b) {
int n = a.size();
int m = a[0].size();
int k = b[0].size();
vvi res(n, vi(k));
for (int i = 0; i < n; i++)
for (int j = 0; j < k; j++)
for (int p = 0; p < m; p++)
res[i][j] = (res[i][j] + (long long) a[i][p] * b[p][j]) % mod;
return res;
}
vvi matrixPow(const vvi &a, int p) {
if (p == 0)
return matrixUnit(a.size());
if (p & 1)
return matrixMul(a, matrixPow(a, p - 1));
return matrixPow(matrixMul(a, a), p / 2);
}
vvi matrixPowSum(const vvi &a, int p) {
int n = a.size();
if (p == 0)
return vvi(n, vi(n));
if (p % 2 == 0)
return matrixMul(matrixPowSum(a, p / 2), matrixAdd(matrixUnit(n), matrixPow(a, p / 2)));
return matrixAdd(a, matrixMul(matrixPowSum(a, p - 1), a));
}
int main() {
vvi a(2, vi(2));
a[0][0] = 1;
a[0][1] = 1;
a[1][0] = 1;
vvi b = matrixPow(a, 10);
}

View File

@ -0,0 +1,87 @@
#include <algorithm>
#include <vector>
#include <climits>
#include <iostream>
using namespace std;
const int maxnodes = 5000;
int nodes = maxnodes, src, dest;
int dist[maxnodes], q[maxnodes], work[maxnodes];
struct Edge {
int to, rev;
int f, cap;
};
vector<Edge> g[maxnodes];
// Adds bidirectional edge
void addEdge(int s, int t, int cap){
Edge a = {t, g[t].size(), 0, cap};
Edge b = {s, g[s].size(), 0, cap};
g[s].push_back(a);
g[t].push_back(b);
}
bool dinic_bfs() {
fill(dist, dist + nodes, -1);
dist[src] = 0;
int qt = 0;
q[qt++] = src;
for (int qh = 0; qh < qt; qh++) {
int u = q[qh];
for (int j = 0; j < (int) g[u].size(); j++) {
Edge &e = g[u][j];
int v = e.to;
if (dist[v] < 0 && e.f < e.cap) {
dist[v] = dist[u] + 1;
q[qt++] = v;
}
}
}
return dist[dest] >= 0;
}
int dinic_dfs(int u, int f) {
if (u == dest)
return f;
for (int &i = work[u]; i < (int) g[u].size(); i++) {
Edge &e = g[u][i];
if (e.cap <= e.f) continue;
int v = e.to;
if (dist[v] == dist[u] + 1) {
int df = dinic_dfs(v, min(f, e.cap - e.f));
if (df > 0) {
e.f += df;
g[v][e.rev].f -= df;
return df;
}
}
}
return 0;
}
int maxFlow(int _src, int _dest) {
src = _src;
dest = _dest;
int result = 0;
while (dinic_bfs()) {
fill(work, work + nodes, 0);
while (int delta = dinic_dfs(src, INT_MAX))
result += delta;
}
return result;
}
int main() {
int n = 3;
nodes = n;
int capacity[][3] = { { 0, 3, 2 }, { 0, 0, 2 }, { 0, 0, 0 } };
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (capacity[i][j] != 0)
addEdge(i, j, capacity[i][j]);
cout << (4 == maxFlow(0, 2)) << endl;
}

86
c++/Basic/MaxMatching.cpp Normal file
View File

@ -0,0 +1,86 @@
#include <algorithm>
#include <iostream>
using namespace std;
const int MAXN1 = 50000;
const int MAXN2 = 50000;
const int MAXM = 150000;
int n1, n2, edges, last[MAXN1], prev[MAXM], head[MAXM];
int matching[MAXN2], dist[MAXN1], Q[MAXN1];
bool used[MAXN1], vis[MAXN1];
void init(int _n1, int _n2) {
n1 = _n1;
n2 = _n2;
edges = 0;
fill(last, last + n1, -1);
}
void addEdge(int u, int v) {
head[edges] = v;
prev[edges] = last[u];
last[u] = edges++;
}
void bfs() {
fill(dist, dist + n1, -1);
int sizeQ = 0;
for (int u = 0; u < n1; ++u) {
if (!used[u]) {
Q[sizeQ++] = u;
dist[u] = 0;
}
}
for (int i = 0; i < sizeQ; i++) {
int u1 = Q[i];
for (int e = last[u1]; e >= 0; e = prev[e]) {
int u2 = matching[head[e]];
if (u2 >= 0 && dist[u2] < 0) {
dist[u2] = dist[u1] + 1;
Q[sizeQ++] = u2;
}
}
}
}
bool dfs(int u1) {
vis[u1] = true;
for (int e = last[u1]; e >= 0; e = prev[e]) {
int v = head[e];
int u2 = matching[v];
if (u2 < 0 || !vis[u2] && dist[u2] == dist[u1] + 1 && dfs(u2)) {
matching[v] = u1;
used[u1] = true;
return true;
}
}
return false;
}
int maxMatching() {
fill(used, used + n1, false);
fill(matching, matching + n2, -1);
for (int res = 0;;) {
bfs();
fill(vis, vis + n1, false);
int f = 0;
for (int u = 0; u < n1; ++u)
if (!used[u] && dfs(u))
++f;
if (!f)
return res;
res += f;
}
}
int main() {
init(2, 2);
addEdge(0, 0);
addEdge(0, 1);
addEdge(1, 1);
cout << (2 == maxMatching()) << endl;
}

121
c++/Basic/MinCostFlow.cpp Normal file
View File

@ -0,0 +1,121 @@
#include <queue>
#include <vector>
#include <climits>
#include <iostream>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int maxnodes = 200000;
int nodes = maxnodes;
int prio[maxnodes], curflow[maxnodes], prevedge[maxnodes], prevnode[maxnodes], q[maxnodes], pot[maxnodes];
bool inqueue[maxnodes];
struct Edge {
int to, f, cap, cost, rev;
};
vector<Edge> graph[maxnodes];
void addEdge(int s, int t, int cap, int cost) {
Edge a = {t, 0, cap, cost, graph[t].size()};
Edge b = {s, 0, 0, -cost, graph[s].size()};
graph[s].push_back(a);
graph[t].push_back(b);
}
void bellmanFord(int s, int dist[]) {
fill(dist, dist + nodes, INT_MAX);
dist[s] = 0;
int qt = 0;
q[qt++] = s;
for (int qh = 0; (qh - qt) % nodes != 0; qh++) {
int u = q[qh % nodes];
inqueue[u] = false;
for (int i = 0; i < (int) graph[u].size(); i++) {
Edge &e = graph[u][i];
if (e.cap <= e.f) continue;
int v = e.to;
int ndist = dist[u] + e.cost;
if (dist[v] > ndist) {
dist[v] = ndist;
if (!inqueue[v]) {
inqueue[v] = true;
q[qt++ % nodes] = v;
}
}
}
}
}
pii minCostFlow(int s, int t, int maxf) {
// bellmanFord can be safely commented if edges costs are non-negative
bellmanFord(s, pot);
int flow = 0;
int flowCost = 0;
while (flow < maxf) {
priority_queue<ll, vector<ll>, greater<ll> > q;
q.push(s);
fill(prio, prio + nodes, INT_MAX);
prio[s] = 0;
curflow[s] = INT_MAX;
while (!q.empty()) {
ll cur = q.top();
int d = cur >> 32;
int u = cur;
q.pop();
if (d != prio[u])
continue;
for (int i = 0; i < (int) graph[u].size(); i++) {
Edge &e = graph[u][i];
int v = e.to;
if (e.cap <= e.f) continue;
int nprio = prio[u] + e.cost + pot[u] - pot[v];
if (prio[v] > nprio) {
prio[v] = nprio;
q.push(((ll) nprio << 32) + v);
prevnode[v] = u;
prevedge[v] = i;
curflow[v] = min(curflow[u], e.cap - e.f);
}
}
}
if (prio[t] == INT_MAX)
break;
for (int i = 0; i < nodes; i++)
pot[i] += prio[i];
int df = min(curflow[t], maxf - flow);
flow += df;
for (int v = t; v != s; v = prevnode[v]) {
Edge &e = graph[prevnode[v]][prevedge[v]];
e.f += df;
graph[v][e.rev].f -= df;
flowCost += df * e.cost;
}
}
return make_pair(flow, flowCost);
}
// Usage example
int main() {
int capacity[3][3] = {
{ 0, 3, 2},
{ 0, 0, 2},
{ 0, 0, 0}
};
nodes = 3;
for (int i = 0; i < nodes; i++)
for (int j = 0; j < nodes; j++)
if (capacity[i][j] != 0)
addEdge(i, j, capacity[i][j], 1);
int s = 0;
int t = 2;
pii res = minCostFlow(s, t, INT_MAX);
int flow = res.first;
int flowCost = res.second;
cout << (4 == flow) << endl;
cout << (6 == flowCost) << endl;
}

View File

@ -0,0 +1,92 @@
#include <queue>
#include <vector>
#include <climits>
#include <iostream>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int maxnodes = 200000;
int nodes = maxnodes;
int prio[maxnodes], curflow[maxnodes], prevedge[maxnodes], prevnode[maxnodes], q[maxnodes];
bool inqueue[maxnodes];
struct Edge {
int to, f, cap, cost, rev;
};
vector<Edge> graph[maxnodes];
void addEdge(int s, int t, int cap, int cost){
Edge a = {t, 0, cap, cost, graph[t].size()};
Edge b = {s, 0, 0, -cost, graph[s].size()};
graph[s].push_back(a);
graph[t].push_back(b);
}
void bellmanFord(int s) {
fill(prio, prio + nodes, INT_MAX);
prio[s] = 0;
int qt = 0;
q[qt++] = s;
for (int qh = 0; (qh - qt) % nodes != 0; qh++) {
int u = q[qh % nodes];
inqueue[u] = false;
for (int i = 0; i < (int) graph[u].size(); i++) {
Edge &e = graph[u][i];
if(e.cap <= e.f) continue;
int v = e.to;
int ndist = prio[u] + e.cost;
if (prio[v] > ndist) {
prio[v] = ndist;
prevnode[v] = u;
prevedge[v] = i;
curflow[v] = min(curflow[u], e.cap - e.f);
if (!inqueue[v]) {
inqueue[v] = true;
q[qt++ % nodes] = v;
}
}
}
}
}
pii minCostFlow(int s, int t, int maxf) {
int flow = 0;
int flowCost = 0;
while (flow < maxf) {
curflow[s] = INT_MAX;
bellmanFord(s);
if (prio[t] == INT_MAX)
break;
int df = min(curflow[t], maxf - flow);
flow += df;
for (int v = t; v != s; v = prevnode[v]) {
Edge &e = graph[prevnode[v]][prevedge[v]];
e.f += df;
graph[v][e.rev].f -= df;
flowCost += df * e.cost;
}
}
return make_pair(flow, flowCost);
}
// Usage example
int main() {
int capacity[3][3] = { { 0, 3, 2 }, { 0, 0, 2 }, { 0, 0, 0 } };
int n = 3;
nodes = n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (capacity[i][j] != 0)
addEdge(i, j, capacity[i][j], 1);
int s = 0;
int t = 2;
pii res = minCostFlow(s, t, INT_MAX);
int flow = res.first;
int flowCost = res.second;
cout << (4 == flow) << endl;
cout << (6 == flowCost) << endl;
}

19
c++/Basic/Odd or Even.cpp Normal file
View File

@ -0,0 +1,19 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n%2 == 0)
{
cout << n << " is even.";
}
else
{
cout << n << " is odd.";
}
getch();
}

18
c++/Basic/Pattern 1.cpp Normal file
View File

@ -0,0 +1,18 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing first pattern (Floyds triangle)
int rows,i,j,k=0;
cout<<"Enter number of rows: ";
cin>>rows;
for(i=1; i<=rows; i++)
{
for(j=1; j<=i; ++j)
cout<<k+j<<" ";
++k;
cout<<endl;
}
getch(); // wait for input
}

31
c++/Basic/Pattern 10.cpp Normal file
View File

@ -0,0 +1,31 @@
//Floyds Triangle
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing pattern
int rows,i,j,space;
cout<<"Enter number of rows: ";
cin>>rows;
for(i=rows; i>=1; --i)
{
for(space=0; space<rows-i; ++space)
cout<<" ";
for(j=i; j<=2*i-1; ++j)
cout<<"* ";
for(j=0; j<i-1; ++j)
cout<<"* ";
cout<<endl;
}
getch(); // wait for input
}
/*
*********
*******
*****
***
*
*/

27
c++/Basic/Pattern 2.cpp Normal file
View File

@ -0,0 +1,27 @@
//Pascal Triangle
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing first pattern (Pascals triangle)
int rows,coef=1,space,i,j;
cout<<"Enter number of rows: ";
cin>>rows;
for(i=0; i<rows; i++)
{
for(space=1; space<=rows-i; space++)
cout<<" ";
for(j=0; j<=i; j++)
{
if (j==0||i==0)
coef=1;
else
coef=coef*(i-j+1)/j;
cout<<" "<<coef;
}
cout<<endl;
}
getch(); // wait for input
}

27
c++/Basic/Pattern 3.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing pattern
int i,j,rows;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
cout<<"* ";
}
cout<<"\n";
}
getch(); // wait for input
}
/*
*
**
***
****
*****
*/

27
c++/Basic/Pattern 4.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing pattern
int i,j,rows;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
cout<<j<<" ";
}
cout<<"\n";
}
getch(); // wait for input
}
/*
1
12
123
1234
12345
*/

27
c++/Basic/Pattern 5.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing pattern
int i,j;
char input,temp='A';
cout<<"Enter uppercase character you want in triange at last row: ";
cin>>input;
for(i=1; i<=(input-'A'+1); ++i)
{
for(j=1; j<=i; ++j)
cout<<temp<<" ";
++temp;
cout<<endl;
}
getch(); // wait for input
}
/*
A
BB
CCC
DDDD
EEEEE
*/

27
c++/Basic/Pattern 6.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing pattern
int i,j,rows;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
cout<<"* ";
}
cout<<"\n";
}
getch(); // wait for input
}
/*
*****
****
***
**
*
*/

27
c++/Basic/Pattern 7.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing pattern
int i,j,rows;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
cout<<j<<" ";
}
cout<<"\n";
}
getch(); // wait for input
}
/*
12345
1234
123
12
1
*/

34
c++/Basic/Pattern 8.cpp Normal file
View File

@ -0,0 +1,34 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing pattern
int i,space,rows,k=0;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=1; i<=rows; ++i)
{
for(space=1; space<=rows-i; ++space)
{
cout<<" ";
}
while(k!=2*i-1)
{
cout<<"* ";
++k;
}
k=0;
cout<<"\n";
}
getch(); // wait for input
}
/*
*
***
*****
*******
*********
*/

44
c++/Basic/Pattern 9.cpp Normal file
View File

@ -0,0 +1,44 @@
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr(); //clears the previous screen
//Printing pattern
int i,space,rows,k=0,count=0,count1=0;
cout<<"Enter the number of rows: ";
cin>>rows;
for(i=1; i<=rows; ++i)
{
for(space=1; space<=rows-i; ++space)
{
cout<<" ";
++count;
}
while(k!=2*i-1)
{
if (count<=rows-1)
{
cout<<i+k<<" ";
++count;
}
else
{
++count1;
cout<<i+k-2*count1<<" ";
}
++k;
}
count1=count=k=0;
cout<<"\n";
}
getch(); // wait for input
}
/*
1
232
34543
4567654
567898765
*/

55
c++/Basic/Prim.cpp Normal file
View File

@ -0,0 +1,55 @@
#include <vector>
#include <queue>
#include <climits>
#include <iostream>
using namespace std;
typedef pair<int, int> pii;
typedef vector<vector<pii> > Graph;
long long prim(Graph &g, vector<int> &pred) {
int n = g.size();
pred.assign(n, -1);
vector<bool> vis(n);
vector<int> prio(n, INT_MAX);
prio[0] = 0;
priority_queue<pii, vector<pii> , greater<pii> > q;
q.push(make_pair(prio[0] , 0));
long long res = 0;
while (!q.empty()) {
int d = q.top().first;
int u = q.top().second;
q.pop();
if (vis[u])
continue;
vis[u] = true;
res += d;
for (int i = 0; i < (int) g[u].size(); i++) {
int v = g[u][i].first;
if (vis[v])
continue;
int nprio = g[u][i].second;
if (prio[v] > nprio) {
prio[v] = nprio;
pred[v] = u;
q.push(make_pair(nprio, v));
}
}
}
return res;
}
int main() {
Graph g(3);
g[0].push_back(make_pair(1, 10));
g[1].push_back(make_pair(0, 10));
g[1].push_back(make_pair(2, 10));
g[2].push_back(make_pair(1, 10));
g[2].push_back(make_pair(0, 5));
g[0].push_back(make_pair(2, 5));
vector<int> pred;
long long res = prim(g, pred);
cout << res << endl;
}

View File

@ -0,0 +1,43 @@
#include <vector>
#include <iostream>
using namespace std;
vector<int> getPrimes(int n) {
if (n <= 1)
return vector<int>();
vector<bool> prime(n + 1, true);
prime[0] = prime[1] = false;
vector<int> primes;
for (int i = 2; i * i <= n; i++)
if (prime[i]) {
for (int j = i * i; j <= n; j += i)
prime[j] = false;
primes.push_back(i);
}
return primes;
}
bool isPrime(long long n) {
if (n <= 1)
return false;
for (long long i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
int main() {
int n = 31;
vector<int> primes = getPrimes(n);
for (int i = 0; i < primes.size(); i++)
cout << primes[i] << " ";
cout << endl;
for (int i = 0; i <= n; i++)
if (isPrime(i))
cout << i << " ";
}

53
c++/Basic/Scanner.cpp Normal file
View File

@ -0,0 +1,53 @@
#include <cstdio>
#include <memory.h>
const int BUF_SIZE = 65536;
char input[BUF_SIZE];
struct Scanner {
char* curPos;
Scanner() {
fread(input, 1, sizeof(input), stdin);
curPos = input;
}
void ensureCapacity() {
int size = input + BUF_SIZE - curPos;
if (size < 100) {
memcpy(input, curPos, size);
fread(input + size, 1, BUF_SIZE - size, stdin);
curPos = input;
}
}
int nextInt() {
ensureCapacity();
while (*curPos <= ' ')
++curPos;
bool sign = false;
if (*curPos == '-') {
sign = true;
++curPos;
}
int res = 0;
while (*curPos > ' ')
res = res * 10 + (*(curPos++) & 15);
return sign ? -res : res;
}
char nextChar() {
ensureCapacity();
while (*curPos <= ' ')
++curPos;
return *(curPos++);
}
};
int main() {
Scanner sc;
int a = sc.nextInt();
char b = sc.nextChar();
printf("%d %c\n", a, b);
}

View File

@ -0,0 +1,14 @@
/* for windows 7 only */
#include < iostream.h >
#include < stdlib.h >
main()
{
char ch;
cout<<"Do you want to shutdown your computer now (y/n)\n";
cin>>ch;
if (ch == 'y' || ch == 'Y')
system("C:\\WINDOWS\\System32\\shutdown /s");
/*shutdown command*/
return 0;
}

View File

@ -0,0 +1,162 @@
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
unsigned char mask[] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
#define tget(i) ( (t[(i)/8]&mask[(i)%8]) ? 1 : 0 )
#define tset(i, b) t[(i)/8]=(b) ? (mask[(i)%8]|t[(i)/8]) : ((~mask[(i)%8])&t[(i)/8])
#define chr(i) (cs==sizeof(int)?((int*)s)[i]:((unsigned char *)s)[i])
#define isLMS(i) (i>0 && tget(i) && !tget(i-1))
// find the start or end of each bucket
void getBuckets(unsigned char *s, int *bkt, int n, int K, int cs, bool end) {
int i, sum = 0;
for (i = 0; i <= K; i++)
bkt[i] = 0; // clear all buckets
for (i = 0; i < n; i++)
bkt[chr(i)]++; // compute the size of each bucket
for (i = 0; i <= K; i++) {
sum += bkt[i];
bkt[i] = end ? sum : sum - bkt[i];
}
}
// compute SAl
void induceSAl(unsigned char *t, int *SA, unsigned char *s, int *bkt, int n, int K, int cs, bool end) {
int i, j;
getBuckets(s, bkt, n, K, cs, end); // find starts of buckets
for (i = 0; i < n; i++) {
j = SA[i] - 1;
if (j >= 0 && !tget(j))
SA[bkt[chr(j)]++] = j;
}
}
// compute SAs
void induceSAs(unsigned char *t, int *SA, unsigned char *s, int *bkt, int n, int K, int cs, bool end) {
int i, j;
getBuckets(s, bkt, n, K, cs, end); // find ends of buckets
for (i = n - 1; i >= 0; i--) {
j = SA[i] - 1;
if (j >= 0 && tget(j))
SA[--bkt[chr(j)]] = j;
}
}
// find the suffix array SA of s[0..n-1] in {1..K}^n
// require s[n-1]=0 (the sentinel!), n>=2
// use a working space (excluding s and SA) of at most 2.25n+O(1) for a constant alphabet
void SA_IS(unsigned char *s, int *SA, int n, int K, int cs) {
int i, j;
unsigned char *t = (unsigned char *) malloc(n / 8 + 1); // LS-type array in bits
// Classify the type of each character
tset(n-2, 0);
tset(n-1, 1); // the sentinel must be in s1, important!!!
for (i = n - 3; i >= 0; i--)
tset(i, (chr(i)<chr(i+1) || (chr(i)==chr(i+1) && tget(i+1)==1))?1:0);
// stage 1: reduce the problem by at least 1/2
// sort all the S-substrings
int *bkt = (int *) malloc(sizeof(int) * (K + 1)); // bucket array
getBuckets(s, bkt, n, K, cs, true); // find ends of buckets
for (i = 0; i < n; i++)
SA[i] = -1;
for (i = 1; i < n; i++)
if (isLMS(i))
SA[--bkt[chr(i)]] = i;
induceSAl(t, SA, s, bkt, n, K, cs, false);
induceSAs(t, SA, s, bkt, n, K, cs, true);
free(bkt);
// compact all the sorted substrings into the first n1 items of SA
// 2*n1 must be not larger than n (proveable)
int n1 = 0;
for (i = 0; i < n; i++)
if (isLMS(SA[i]))
SA[n1++] = SA[i];
// find the lexicographic names of all substrings
for (i = n1; i < n; i++)
SA[i] = -1; // init the name array buffer
int name = 0, prev = -1;
for (i = 0; i < n1; i++) {
int pos = SA[i];
bool diff = false;
for (int d = 0; d < n; d++)
if (prev == -1 || chr(pos+d) != chr(prev+d) || tget(pos+d) != tget(prev+d)) {
diff = true;
break;
} else if (d > 0 && (isLMS(pos+d) || isLMS(prev+d)))
break;
if (diff) {
name++;
prev = pos;
}
pos = (pos % 2 == 0) ? pos / 2 : (pos - 1) / 2;
SA[n1 + pos] = name - 1;
}
for (i = n - 1, j = n - 1; i >= n1; i--)
if (SA[i] >= 0)
SA[j--] = SA[i];
// stage 2: solve the reduced problem
// recurse if names are not yet unique
int *SA1 = SA, *s1 = SA + n - n1;
if (name < n1)
SA_IS((unsigned char*) s1, SA1, n1, name - 1, sizeof(int));
else
// generate the suffix array of s1 directly
for (i = 0; i < n1; i++)
SA1[s1[i]] = i;
// stage 3: induce the result for the original problem
bkt = (int *) malloc(sizeof(int) * (K + 1)); // bucket array
// put all left-most S characters into their buckets
getBuckets(s, bkt, n, K, cs, true); // find ends of buckets
for (i = 1, j = 0; i < n; i++)
if (isLMS(i))
s1[j++] = i; // get p1
for (i = 0; i < n1; i++)
SA1[i] = s1[SA1[i]]; // get index in s
for (i = n1; i < n; i++)
SA[i] = -1; // init SA[n1..n-1]
for (i = n1 - 1; i >= 0; i--) {
j = SA[i];
SA[i] = -1;
SA[--bkt[chr(j)]] = j;
}
induceSAl(t, SA, s, bkt, n, K, cs, false);
induceSAs(t, SA, s, bkt, n, K, cs, true);
free(bkt);
free(t);
}
const int maxn = 200000;
int sa[maxn];
int lcp[maxn];
int Rank[maxn];
unsigned char *s;
int n;
void calc_lcp() {
for (int i = 0; i < n; i++)
Rank[sa[i]] = i;
for (int i = 0, h = 0; i < n; i++) {
if (Rank[i] < n - 1) {
for (int j = sa[Rank[i] + 1]; s[i + h] == s[j + h]; ++h)
;
lcp[Rank[i]] = h;
if (h > 0)
--h;
}
}
}
int main() {
string str = "abcab";
n = str.size();
s = (unsigned char*) str.c_str();
SA_IS(s, sa, n + 1, 256, 1);
calc_lcp();
for (int i = 0; i < n; i++) {
cout << str.substr(sa[i + 1]);
if (i < n - 1)
cout << " " << lcp[i + 1];
cout << endl;
}
}

View File

@ -0,0 +1,164 @@
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
vvi children, subtreeLabels, tree, L;
vi pred, map;
int n;
bool compare(int a, int b) {
return subtreeLabels[a] < subtreeLabels[b];
}
bool equals(int a, int b) {
return subtreeLabels[a] == subtreeLabels[b];
}
void generateMapping(int r1, int r2) {
map.resize(n);
map[r1] = r2 - n;
sort(children[r1].begin(), children[r1].end(), compare);
sort(children[r2].begin(), children[r2].end(), compare);
for (int i = 0; i < (int) children[r1].size(); i++) {
int u = children[r1][i];
int v = children[r2][i];
generateMapping(u, v);
}
}
vi findCenter(int offset = 0) {
int cnt = n;
vi a;
vi deg(n);
for (int i = 0; i < n; i++) {
deg[i] = tree[i + offset].size();
if (deg[i] <= 1) {
a.push_back(i + offset);
--cnt;
}
}
while (cnt > 0) {
vi na;
for (int i = 0; i < (int) a.size(); i++) {
int u = a[i];
for (int j = 0; j < (int) tree[u].size(); j++) {
int v = tree[u][j];
if (--deg[v - offset] == 1) {
na.push_back(v);
--cnt;
}
}
}
a = na;
}
return a;
}
int dfs(int u, int p = -1, int depth = 0) {
L[depth].push_back(u);
int h = 0;
for (int i = 0; i < (int) tree[u].size(); i++) {
int v = tree[u][i];
if (v == p)
continue;
pred[v] = u;
children[u].push_back(v);
h = max(h, dfs(v, u, depth + 1));
}
return h + 1;
}
bool rootedTreeIsomorphism(int r1, int r2) {
L.assign(n, vi());
pred.assign(2 * n, -1);
children.assign(2 * n, vi());
int h1 = dfs(r1);
int h2 = dfs(r2);
if (h1 != h2)
return false;
int h = h1 - 1;
vi label(2 * n);
subtreeLabels.assign(2 * n, vi());
for (int i = h - 1; i >= 0; i--) {
for (int j = 0; j < (int) L[i + 1].size(); j++) {
int v = L[i + 1][j];
subtreeLabels[pred[v]].push_back(label[v]);
}
sort(L[i].begin(), L[i].end(), compare);
for (int j = 0, cnt = 0; j < (int) L[i].size(); j++) {
if (j && !equals(L[i][j], L[i][j - 1]))
++cnt;
label[L[i][j]] = cnt;
}
}
if (!equals(r1, r2))
return false;
generateMapping(r1, r2);
return true;
}
bool treeIsomorphism() {
vi c1 = findCenter();
vi c2 = findCenter(n);
if (c1.size() == c2.size()) {
if (rootedTreeIsomorphism(c1[0], c2[0]))
return true;
else if (c1.size() > 1)
return rootedTreeIsomorphism(c1[1], c2[0]);
}
return false;
}
int main() {
n = 5;
vvi t1(n);
t1[0].push_back(1);
t1[1].push_back(0);
t1[1].push_back(2);
t1[2].push_back(1);
t1[1].push_back(3);
t1[3].push_back(1);
t1[0].push_back(4);
t1[4].push_back(0);
vvi t2(n);
t2[0].push_back(1);
t2[1].push_back(0);
t2[0].push_back(4);
t2[4].push_back(0);
t2[4].push_back(3);
t2[3].push_back(4);
t2[4].push_back(2);
t2[2].push_back(4);
tree.assign(2 * n, vi());
for (int u = 0; u < n; u++) {
for (int i = 0; i < t1[u].size(); i++) {
int v = t1[u][i];
tree[u].push_back(v);
}
for (int i = 0; i < t2[u].size(); i++) {
int v = t2[u][i];
tree[u + n].push_back(v + n);
}
}
bool res = treeIsomorphism();
cout << res << endl;
if (res)
for (int i = 0; i < n; i++)
cout << map[i] << endl;
}

506
c++/Basic/bigint-full.cpp Normal file
View File

@ -0,0 +1,506 @@
#include <vector>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <complex>
#include <ctime>
#include <cstdio>
using namespace std;
// base and base_digits must be consistent
const int base = 1000000000;
const int base_digits = 9;
struct bigint {
vector<int> a;
int sign;
bigint() :
sign(1) {
}
bigint(long long v) {
*this = v;
}
bigint(const string &s) {
read(s);
}
void operator=(const bigint &v) {
sign = v.sign;
a = v.a;
}
void operator=(long long v) {
sign = 1;
if (v < 0)
sign = -1, v = -v;
a.clear();
for (; v > 0; v = v / base)
a.push_back(v % base);
}
bigint operator+(const bigint &v) const {
if (sign == v.sign) {
bigint res = v;
for (int i = 0, carry = 0; i < (int) max(a.size(), v.a.size()) || carry; ++i) {
if (i == (int) res.a.size())
res.a.push_back(0);
res.a[i] += carry + (i < (int) a.size() ? a[i] : 0);
carry = res.a[i] >= base;
if (carry)
res.a[i] -= base;
}
return res;
}
return *this - (-v);
}
bigint operator-(const bigint &v) const {
if (sign == v.sign) {
if (abs() >= v.abs()) {
bigint res = *this;
for (int i = 0, carry = 0; i < (int) v.a.size() || carry; ++i) {
res.a[i] -= carry + (i < (int) v.a.size() ? v.a[i] : 0);
carry = res.a[i] < 0;
if (carry)
res.a[i] += base;
}
res.trim();
return res;
}
return -(v - *this);
}
return *this + (-v);
}
void operator*=(int v) {
if (v < 0)
sign = -sign, v = -v;
for (int i = 0, carry = 0; i < (int) a.size() || carry; ++i) {
if (i == (int) a.size())
a.push_back(0);
long long cur = a[i] * (long long) v + carry;
carry = (int) (cur / base);
a[i] = (int) (cur % base);
//asm("divl %%ecx" : "=a"(carry), "=d"(a[i]) : "A"(cur), "c"(base));
/*
int val;
__asm {
lea esi, cur
mov eax, [esi]
mov edx, [esi+4]
mov ecx, base
div ecx
mov carry, eax
mov val, edx;
}
a[i] = val;
*/
}
trim();
}
bigint operator*(int v) const {
bigint res = *this;
res *= v;
return res;
}
friend pair<bigint, bigint> divmod(const bigint &a1, const bigint &b1) {
int norm = base / (b1.a.back() + 1);
bigint a = a1.abs() * norm;
bigint b = b1.abs() * norm;
bigint q, r;
q.a.resize(a.a.size());
for (int i = a.a.size() - 1; i >= 0; i--) {
r *= base;
r += a.a[i];
int s1 = r.a.size() <= b.a.size() ? 0 : r.a[b.a.size()];
int s2 = r.a.size() <= b.a.size() - 1 ? 0 : r.a[b.a.size() - 1];
int d = ((long long) base * s1 + s2) / b.a.back();
r -= b * d;
while (r < 0)
r += b, --d;
q.a[i] = d;
}
q.sign = a1.sign * b1.sign;
r.sign = a1.sign;
q.trim();
r.trim();
return make_pair(q, r / norm);
}
bigint operator/(const bigint &v) const {
return divmod(*this, v).first;
}
bigint operator%(const bigint &v) const {
return divmod(*this, v).second;
}
void operator/=(int v) {
if (v < 0)
sign = -sign, v = -v;
for (int i = (int) a.size() - 1, rem = 0; i >= 0; --i) {
long long cur = a[i] + rem * (long long) base;
a[i] = (int) (cur / v);
rem = (int) (cur % v);
}
trim();
}
bigint operator/(int v) const {
bigint res = *this;
res /= v;
return res;
}
int operator%(int v) const {
if (v < 0)
v = -v;
int m = 0;
for (int i = a.size() - 1; i >= 0; --i)
m = (a[i] + m * (long long) base) % v;
return m * sign;
}
void operator+=(const bigint &v) {
*this = *this + v;
}
void operator-=(const bigint &v) {
*this = *this - v;
}
void operator*=(const bigint &v) {
*this = *this * v;
}
void operator/=(const bigint &v) {
*this = *this / v;
}
bool operator<(const bigint &v) const {
if (sign != v.sign)
return sign < v.sign;
if (a.size() != v.a.size())
return a.size() * sign < v.a.size() * v.sign;
for (int i = a.size() - 1; i >= 0; i--)
if (a[i] != v.a[i])
return a[i] * sign < v.a[i] * sign;
return false;
}
bool operator>(const bigint &v) const {
return v < *this;
}
bool operator<=(const bigint &v) const {
return !(v < *this);
}
bool operator>=(const bigint &v) const {
return !(*this < v);
}
bool operator==(const bigint &v) const {
return !(*this < v) && !(v < *this);
}
bool operator!=(const bigint &v) const {
return *this < v || v < *this;
}
void trim() {
while (!a.empty() && a.back() == 0)
a.pop_back();
if (a.empty())
sign = 1;
}
bool isZero() const {
return a.empty() || (a.size() == 1 && !a[0]);
}
bigint operator-() const {
bigint res = *this;
res.sign = -sign;
return res;
}
bigint abs() const {
bigint res = *this;
res.sign *= res.sign;
return res;
}
long long longValue() const {
long long res = 0;
for (int i = a.size() - 1; i >= 0; i--)
res = res * base + a[i];
return res * sign;
}
friend bigint gcd(const bigint &a, const bigint &b) {
return b.isZero() ? a : gcd(b, a % b);
}
friend bigint lcm(const bigint &a, const bigint &b) {
return a / gcd(a, b) * b;
}
void read(const string &s) {
sign = 1;
a.clear();
int pos = 0;
while (pos < (int) s.size() && (s[pos] == '-' || s[pos] == '+')) {
if (s[pos] == '-')
sign = -sign;
++pos;
}
for (int i = s.size() - 1; i >= pos; i -= base_digits) {
int x = 0;
for (int j = max(pos, i - base_digits + 1); j <= i; j++)
x = x * 10 + s[j] - '0';
a.push_back(x);
}
trim();
}
friend istream& operator>>(istream &stream, bigint &v) {
string s;
stream >> s;
v.read(s);
return stream;
}
friend ostream& operator<<(ostream &stream, const bigint &v) {
if (v.sign == -1)
stream << '-';
stream << (v.a.empty() ? 0 : v.a.back());
for (int i = (int) v.a.size() - 2; i >= 0; --i)
stream << setw(base_digits) << setfill('0') << v.a[i];
return stream;
}
static vector<int> convert_base(const vector<int> &a, int old_digits, int new_digits) {
vector<long long> p(max(old_digits, new_digits) + 1);
p[0] = 1;
for (int i = 1; i < (int) p.size(); i++)
p[i] = p[i - 1] * 10;
vector<int> res;
long long cur = 0;
int cur_digits = 0;
for (int i = 0; i < (int) a.size(); i++) {
cur += a[i] * p[cur_digits];
cur_digits += old_digits;
while (cur_digits >= new_digits) {
res.push_back(int(cur % p[new_digits]));
cur /= p[new_digits];
cur_digits -= new_digits;
}
}
res.push_back((int) cur);
while (!res.empty() && res.back() == 0)
res.pop_back();
return res;
}
void fft(vector<complex<double> > & a, bool invert) const {
int n = (int) a.size();
for (int i = 1, j = 0; i < n; ++i) {
int bit = n >> 1;
for (; j >= bit; bit >>= 1)
j -= bit;
j += bit;
if (i < j)
swap(a[i], a[j]);
}
for (int len = 2; len <= n; len <<= 1) {
double ang = 2 * 3.14159265358979323846 / len * (invert ? -1 : 1);
complex<double> wlen(cos(ang), sin(ang));
for (int i = 0; i < n; i += len) {
complex<double> w(1);
for (int j = 0; j < len / 2; ++j) {
complex<double> u = a[i + j];
complex<double> v = a[i + j + len / 2] * w;
a[i + j] = u + v;
a[i + j + len / 2] = u - v;
w *= wlen;
}
}
}
if (invert)
for (int i = 0; i < n; ++i)
a[i] /= n;
}
void multiply_fft(const vector<int> &a, const vector<int> &b, vector<int> &res) const {
vector<complex<double> > fa(a.begin(), a.end());
vector<complex<double> > fb(b.begin(), b.end());
int n = 1;
while (n < (int) max(a.size(), b.size()))
n <<= 1;
n <<= 1;
fa.resize(n);
fb.resize(n);
fft(fa, false);
fft(fb, false);
for (int i = 0; i < n; ++i)
fa[i] *= fb[i];
fft(fa, true);
res.resize(n);
for (int i = 0, carry = 0; i < n; ++i) {
res[i] = int(fa[i].real() + 0.5) + carry;
carry = res[i] / 1000;
res[i] %= 1000;
}
}
bigint operator*(const bigint &v) const {
bigint res;
res.sign = sign * v.sign;
multiply_fft(convert_base(a, base_digits, 3), convert_base(v.a, base_digits, 3), res.a);
res.a = convert_base(res.a, 3, base_digits);
res.trim();
return res;
}
bigint mul_simple(const bigint &v) const {
bigint res;
res.sign = sign * v.sign;
res.a.resize(a.size() + v.a.size());
for (int i = 0; i < (int) a.size(); ++i)
if (a[i])
for (int j = 0, carry = 0; j < (int) v.a.size() || carry; ++j) {
long long cur = res.a[i + j] + (long long) a[i] * (j < (int) v.a.size() ? v.a[j] : 0) + carry;
carry = (int) (cur / base);
res.a[i + j] = (int) (cur % base);
}
res.trim();
return res;
}
typedef vector<long long> vll;
static vll karatsubaMultiply(const vll &a, const vll &b) {
int n = a.size();
vll res(n + n);
if (n <= 32) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
res[i + j] += a[i] * b[j];
return res;
}
int k = n >> 1;
vll a1(a.begin(), a.begin() + k);
vll a2(a.begin() + k, a.end());
vll b1(b.begin(), b.begin() + k);
vll b2(b.begin() + k, b.end());
vll a1b1 = karatsubaMultiply(a1, b1);
vll a2b2 = karatsubaMultiply(a2, b2);
for (int i = 0; i < k; i++)
a2[i] += a1[i];
for (int i = 0; i < k; i++)
b2[i] += b1[i];
vll r = karatsubaMultiply(a2, b2);
for (int i = 0; i < (int) a1b1.size(); i++)
r[i] -= a1b1[i];
for (int i = 0; i < (int) a2b2.size(); i++)
r[i] -= a2b2[i];
for (int i = 0; i < (int) r.size(); i++)
res[i + k] += r[i];
for (int i = 0; i < (int) a1b1.size(); i++)
res[i] += a1b1[i];
for (int i = 0; i < (int) a2b2.size(); i++)
res[i + n] += a2b2[i];
return res;
}
bigint mul_karatsuba(const bigint &v) const {
vector<int> a6 = convert_base(this->a, base_digits, 6);
vector<int> b6 = convert_base(v.a, base_digits, 6);
vll a(a6.begin(), a6.end());
vll b(b6.begin(), b6.end());
while (a.size() < b.size())
a.push_back(0);
while (b.size() < a.size())
b.push_back(0);
while (a.size() & (a.size() - 1))
a.push_back(0), b.push_back(0);
vll c = karatsubaMultiply(a, b);
bigint res;
res.sign = sign * v.sign;
for (int i = 0, carry = 0; i < (int) c.size(); i++) {
long long cur = c[i] + carry;
res.a.push_back((int) (cur % 1000000));
carry = (int) (cur / 1000000);
}
res.a = convert_base(res.a, 6, base_digits);
res.trim();
return res;
}
};
bigint getRandomBigint(int len) {
string s;
for (int i = 0; i < len; i++)
s += rand() % 10 + '0';
return bigint(s);
}
int main() {
srand(1);
bigint a("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999");
bigint b("19999999999999999999999999999999999999999999999999999999999999999999999999999999999999998");
cout << a * b << endl;
cout << a.mul_karatsuba(b) << endl;
cout << a / b << endl;
for (int step = 0; step < 100; step++) {
bigint a = getRandomBigint(1000);
bigint b = getRandomBigint(1000);
bigint x = a * b;
bigint y = a.mul_simple(b);
bigint z = a.mul_karatsuba(b);
if (x != y || x != z) {
cout << a << " " << b << " " << x << " " << y << " " << z << endl;
}
}
int steps = 1;
vector<bigint> x(steps), y(steps);
for (int i = 0; i < steps; i++) {
x[i] = getRandomBigint(60000);
y[i] = getRandomBigint(60000);
}
clock_t start = clock();
for (int i = 0; i < steps; i++)
bigint z = x[i] * y[i];
fprintf(stderr, "time=%.3lfsec\n", 0.001 * (clock() - start));
start = clock();
for (int i = 0; i < steps; i++)
bigint z = x[i].mul_karatsuba(y[i]);
fprintf(stderr, "time=%.3lfsec\n", 0.001 * (clock() - start));
a = getRandomBigint(10000);
b = getRandomBigint(2000);
start = clock();
bigint c = a / b;
fprintf(stderr, "time=%.3lfsec\n", 0.001 * (clock() - start));
bigint z = 5;
z = 6;
cout << z << endl;
}

446
c++/Basic/bigint.cpp Normal file
View File

@ -0,0 +1,446 @@
#include <vector>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdio>
#include <cmath>
using namespace std;
// base and base_digits must be consistent
const int base = 1000000000;
const int base_digits = 9;
struct bigint {
vector<int> z;
int sign;
bigint() :
sign(1) {
}
bigint(long long v) {
*this = v;
}
bigint(const string &s) {
read(s);
}
void operator=(const bigint &v) {
sign = v.sign;
z = v.z;
}
void operator=(long long v) {
sign = 1;
if (v < 0)
sign = -1, v = -v;
z.clear();
for (; v > 0; v = v / base)
z.push_back(v % base);
}
bigint operator+(const bigint &v) const {
if (sign == v.sign) {
bigint res = v;
for (int i = 0, carry = 0; i < (int) max(z.size(), v.z.size()) || carry; ++i) {
if (i == (int) res.z.size())
res.z.push_back(0);
res.z[i] += carry + (i < (int) z.size() ? z[i] : 0);
carry = res.z[i] >= base;
if (carry)
res.z[i] -= base;
}
return res;
}
return *this - (-v);
}
bigint operator-(const bigint &v) const {
if (sign == v.sign) {
if (abs() >= v.abs()) {
bigint res = *this;
for (int i = 0, carry = 0; i < (int) v.z.size() || carry; ++i) {
res.z[i] -= carry + (i < (int) v.z.size() ? v.z[i] : 0);
carry = res.z[i] < 0;
if (carry)
res.z[i] += base;
}
res.trim();
return res;
}
return -(v - *this);
}
return *this + (-v);
}
void operator*=(int v) {
if (v < 0)
sign = -sign, v = -v;
for (int i = 0, carry = 0; i < (int) z.size() || carry; ++i) {
if (i == (int) z.size())
z.push_back(0);
long long cur = z[i] * (long long) v + carry;
carry = (int) (cur / base);
z[i] = (int) (cur % base);
//asm("divl %%ecx" : "=a"(carry), "=d"(a[i]) : "A"(cur), "c"(base));
}
trim();
}
bigint operator*(int v) const {
bigint res = *this;
res *= v;
return res;
}
friend pair<bigint, bigint> divmod(const bigint &a1, const bigint &b1) {
int norm = base / (b1.z.back() + 1);
bigint a = a1.abs() * norm;
bigint b = b1.abs() * norm;
bigint q, r;
q.z.resize(a.z.size());
for (int i = a.z.size() - 1; i >= 0; i--) {
r *= base;
r += a.z[i];
int s1 = b.z.size() < r.z.size() ? r.z[b.z.size()] : 0;
int s2 = b.z.size() - 1 < r.z.size() ? r.z[b.z.size() - 1] : 0;
int d = ((long long) s1 * base + s2) / b.z.back();
r -= b * d;
while (r < 0)
r += b, --d;
q.z[i] = d;
}
q.sign = a1.sign * b1.sign;
r.sign = a1.sign;
q.trim();
r.trim();
return make_pair(q, r / norm);
}
friend bigint sqrt(const bigint &a1) {
bigint a = a1;
while (a.z.empty() || a.z.size() % 2 == 1)
a.z.push_back(0);
int n = a.z.size();
int firstDigit = (int) sqrt((double) a.z[n - 1] * base + a.z[n - 2]);
int norm = base / (firstDigit + 1);
a *= norm;
a *= norm;
while (a.z.empty() || a.z.size() % 2 == 1)
a.z.push_back(0);
bigint r = (long long) a.z[n - 1] * base + a.z[n - 2];
firstDigit = (int) sqrt((double) a.z[n - 1] * base + a.z[n - 2]);
int q = firstDigit;
bigint res;
for(int j = n / 2 - 1; j >= 0; j--) {
for(; ; --q) {
bigint r1 = (r - (res * 2 * base + q) * q) * base * base + (j > 0 ? (long long) a.z[2 * j - 1] * base + a.z[2 * j - 2] : 0);
if (r1 >= 0) {
r = r1;
break;
}
}
res *= base;
res += q;
if (j > 0) {
int d1 = res.z.size() + 2 < r.z.size() ? r.z[res.z.size() + 2] : 0;
int d2 = res.z.size() + 1 < r.z.size() ? r.z[res.z.size() + 1] : 0;
int d3 = res.z.size() < r.z.size() ? r.z[res.z.size()] : 0;
q = ((long long) d1 * base * base + (long long) d2 * base + d3) / (firstDigit * 2);
}
}
res.trim();
return res / norm;
}
bigint operator/(const bigint &v) const {
return divmod(*this, v).first;
}
bigint operator%(const bigint &v) const {
return divmod(*this, v).second;
}
void operator/=(int v) {
if (v < 0)
sign = -sign, v = -v;
for (int i = (int) z.size() - 1, rem = 0; i >= 0; --i) {
long long cur = z[i] + rem * (long long) base;
z[i] = (int) (cur / v);
rem = (int) (cur % v);
}
trim();
}
bigint operator/(int v) const {
bigint res = *this;
res /= v;
return res;
}
int operator%(int v) const {
if (v < 0)
v = -v;
int m = 0;
for (int i = z.size() - 1; i >= 0; --i)
m = (z[i] + m * (long long) base) % v;
return m * sign;
}
void operator+=(const bigint &v) {
*this = *this + v;
}
void operator-=(const bigint &v) {
*this = *this - v;
}
void operator*=(const bigint &v) {
*this = *this * v;
}
void operator/=(const bigint &v) {
*this = *this / v;
}
bool operator<(const bigint &v) const {
if (sign != v.sign)
return sign < v.sign;
if (z.size() != v.z.size())
return z.size() * sign < v.z.size() * v.sign;
for (int i = z.size() - 1; i >= 0; i--)
if (z[i] != v.z[i])
return z[i] * sign < v.z[i] * sign;
return false;
}
bool operator>(const bigint &v) const {
return v < *this;
}
bool operator<=(const bigint &v) const {
return !(v < *this);
}
bool operator>=(const bigint &v) const {
return !(*this < v);
}
bool operator==(const bigint &v) const {
return !(*this < v) && !(v < *this);
}
bool operator!=(const bigint &v) const {
return *this < v || v < *this;
}
void trim() {
while (!z.empty() && z.back() == 0)
z.pop_back();
if (z.empty())
sign = 1;
}
bool isZero() const {
return z.empty() || (z.size() == 1 && !z[0]);
}
bigint operator-() const {
bigint res = *this;
res.sign = -sign;
return res;
}
bigint abs() const {
bigint res = *this;
res.sign *= res.sign;
return res;
}
long long longValue() const {
long long res = 0;
for (int i = z.size() - 1; i >= 0; i--)
res = res * base + z[i];
return res * sign;
}
friend bigint gcd(const bigint &a, const bigint &b) {
return b.isZero() ? a : gcd(b, a % b);
}
friend bigint lcm(const bigint &a, const bigint &b) {
return a / gcd(a, b) * b;
}
void read(const string &s) {
sign = 1;
z.clear();
int pos = 0;
while (pos < (int) s.size() && (s[pos] == '-' || s[pos] == '+')) {
if (s[pos] == '-')
sign = -sign;
++pos;
}
for (int i = s.size() - 1; i >= pos; i -= base_digits) {
int x = 0;
for (int j = max(pos, i - base_digits + 1); j <= i; j++)
x = x * 10 + s[j] - '0';
z.push_back(x);
}
trim();
}
friend istream& operator>>(istream &stream, bigint &v) {
string s;
stream >> s;
v.read(s);
return stream;
}
friend ostream& operator<<(ostream &stream, const bigint &v) {
if (v.sign == -1)
stream << '-';
stream << (v.z.empty() ? 0 : v.z.back());
for (int i = (int) v.z.size() - 2; i >= 0; --i)
stream << setw(base_digits) << setfill('0') << v.z[i];
return stream;
}
static vector<int> convert_base(const vector<int> &a, int old_digits, int new_digits) {
vector<long long> p(max(old_digits, new_digits) + 1);
p[0] = 1;
for (int i = 1; i < (int) p.size(); i++)
p[i] = p[i - 1] * 10;
vector<int> res;
long long cur = 0;
int cur_digits = 0;
for (int i = 0; i < (int) a.size(); i++) {
cur += a[i] * p[cur_digits];
cur_digits += old_digits;
while (cur_digits >= new_digits) {
res.push_back(int(cur % p[new_digits]));
cur /= p[new_digits];
cur_digits -= new_digits;
}
}
res.push_back((int) cur);
while (!res.empty() && res.back() == 0)
res.pop_back();
return res;
}
typedef vector<long long> vll;
static vll karatsubaMultiply(const vll &a, const vll &b) {
int n = a.size();
vll res(n + n);
if (n <= 32) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
res[i + j] += a[i] * b[j];
return res;
}
int k = n >> 1;
vll a1(a.begin(), a.begin() + k);
vll a2(a.begin() + k, a.end());
vll b1(b.begin(), b.begin() + k);
vll b2(b.begin() + k, b.end());
vll a1b1 = karatsubaMultiply(a1, b1);
vll a2b2 = karatsubaMultiply(a2, b2);
for (int i = 0; i < k; i++)
a2[i] += a1[i];
for (int i = 0; i < k; i++)
b2[i] += b1[i];
vll r = karatsubaMultiply(a2, b2);
for (int i = 0; i < (int) a1b1.size(); i++)
r[i] -= a1b1[i];
for (int i = 0; i < (int) a2b2.size(); i++)
r[i] -= a2b2[i];
for (int i = 0; i < (int) r.size(); i++)
res[i + k] += r[i];
for (int i = 0; i < (int) a1b1.size(); i++)
res[i] += a1b1[i];
for (int i = 0; i < (int) a2b2.size(); i++)
res[i + n] += a2b2[i];
return res;
}
bigint operator*(const bigint &v) const {
vector<int> a6 = convert_base(this->z, base_digits, 6);
vector<int> b6 = convert_base(v.z, base_digits, 6);
vll a(a6.begin(), a6.end());
vll b(b6.begin(), b6.end());
while (a.size() < b.size())
a.push_back(0);
while (b.size() < a.size())
b.push_back(0);
while (a.size() & (a.size() - 1))
a.push_back(0), b.push_back(0);
vll c = karatsubaMultiply(a, b);
bigint res;
res.sign = sign * v.sign;
for (int i = 0, carry = 0; i < (int) c.size(); i++) {
long long cur = c[i] + carry;
res.z.push_back((int) (cur % 1000000));
carry = (int) (cur / 1000000);
}
res.z = convert_base(res.z, 6, base_digits);
res.trim();
return res;
}
};
bigint random_bigint(int n) {
string s;
for (int i = 0; i < n; i++) {
s += rand() % 10 + '0';
}
return bigint(s);
}
// random tests
int main() {
for(int i = 0; i < 1000; i++) {
cout << i << endl;
int n = rand() % 100 + 1;
bigint a = random_bigint(n);
bigint res = sqrt(a);
bigint xx = res * res;
bigint yy = (res + 1) * (res + 1);
if (xx > a || yy <= a) {
cout << a << " " << res << endl;
break;
}
int m = rand() % n + 1;
bigint b = random_bigint(m) + 1;
res = a / b;
xx = res * b;
yy = b * (res + 1);
if (xx > a || yy <= a) {
cout << a << " " << b << " " << res << endl;
break;
}
}
bigint a = random_bigint(10000);
bigint b = random_bigint(2000);
clock_t start = clock();
bigint c = a / b;
fprintf(stdout, "time=%.3lfsec\n", 0.001 * (clock() - start));
bigint x = 5;
x = 6;
cout << x << endl;
}

41
c++/Basic/nCr & nPr.cpp Normal file
View File

@ -0,0 +1,41 @@
#include < iostream.h >
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
main()
{
int n, r;
long ncr, npr;
cout<<"Enter the value of n and r\n";
cin>>n>>r;
ncr = find_ncr(n, r);
npr = find_npr(n, r);
cout<<n<<"C"<<r<<" ="<<ncr<<"\n";
cout<<n<<"P"<<r<<"=" <<npr<<"\n";
return 0;
}
long find_ncr(int n, int r)
{
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
long find_npr(int n, int r)
{
long result;
result = factorial(n)/factorial(n-r);
return result;
}
long factorial(int n)
{
int c;
long result = 1;
for( c = 1 ; c < = n ; c++ )
result = result*c;
return ( result );
}

View File

@ -0,0 +1,88 @@
#include <vector>
#include <iostream>
#include <iomanip>
#include <complex>
using namespace std;
typedef complex<double> cdouble;
typedef vector<cdouble> poly;
pair<poly, cdouble> horner(const poly &a, cdouble x0) {
int n = a.size();
poly b = poly(max(1, n - 1));
for(int i = n - 1; i > 0; i--)
b[i - 1] = a[i] + (i < n - 1 ? b[i] * x0 : 0);
return make_pair(b, a[0] + b[0] * x0);
}
cdouble eval(const poly &p, cdouble x) {
return horner(p, x).second;
}
poly derivative(const poly &p) {
int n = p.size();
poly r = poly(max(1, n - 1));
for(int i = 1; i < n; i++)
r[i - 1] = p[i] * cdouble(i);
return r;
}
const double EPS = 1e-9;
int cmp(cdouble x, cdouble y) {
double diff = abs(x) - abs(y);
return diff < -EPS ? -1 : (diff > EPS ? 1 : 0);
}
cdouble find_one_root(const poly &p0, cdouble x) {
int n = p0.size() - 1;
poly p1 = derivative(p0);
poly p2 = derivative(p1);
for (int step = 0; step < 10000; step++) {
cdouble y0 = eval(p0, x);
if (cmp(y0, 0) == 0) break;
cdouble G = eval(p1, x) / y0;
cdouble H = G * G - eval(p2, x) - y0;
cdouble R = sqrt(cdouble(n - 1) * (H * cdouble(n) - G * G));
cdouble D1 = G + R;
cdouble D2 = G - R;
cdouble a = cdouble(n) / (cmp(D1, D2) > 0 ? D1 : D2);
x -= a;
if (cmp(a, 0) == 0) break;
}
return x;
}
vector<cdouble> find_all_roots(const poly &p) {
vector<cdouble> res;
poly q = p;
while (q.size() > 2) {
cdouble z(rand() / double(RAND_MAX), rand() / double(RAND_MAX));
z = find_one_root(q, z);
z = find_one_root(p, z);
q = horner(q, z).first;
res.push_back(z);
}
res.push_back(-q[0] / q[1]);
return res;
}
int main( int argc, char* argv[] ) {
poly p;
// x^3 - 8x^2 - 13x + 140 = (x+4)(x-5)(x-7)
p.push_back(140);
p.push_back(-13);
p.push_back(-8);
p.push_back(1);
vector<cdouble> roots = find_all_roots(p);
for(size_t i = 0; i < roots.size(); i++) {
if (abs(roots[i].real()) < EPS) roots[i] -= cdouble(roots[i].real(), 0);
if (abs(roots[i].imag()) < EPS) roots[i] -= cdouble(0, roots[i].imag());
cout << setprecision(3) << roots[i] << endl;
}
return 0;
}

View File

@ -0,0 +1,70 @@
/*This is a C++ Program to perform 2D FFT. A fast Fourier transform (FFT) is an algorithm to compute the discrete Fourier transform (DFT) and its inverse. Fourier analysis converts time (or space) to frequency and vice versa; an FFT rapidly computes such transformations by factorizing the DFT matrix into a product of sparse (mostly zero) factors.*/
#include <iostream>
#include <math.h>
using namespace std;
#define PI 3.14159265
int n;
int main(int argc, char **argv)
{
cout << "Enter the size: ";
cin >> n;
double inputData[n][n];
cout << "Enter the 2D elements ";
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> inputData[i][j];
double realOut[n][n];
double imagOut[n][n];
double amplitudeOut[n][n];
int height = n;
int width = n;
// Two outer loops iterate on output data.
for (int yWave = 0; yWave < height; yWave++)
{
for (int xWave = 0; xWave < width; xWave++)
{
// Two inner loops iterate on input data.
for (int ySpace = 0; ySpace < height; ySpace++)
{
for (int xSpace = 0; xSpace < width; xSpace++)
{
// Compute real, imag, and ampltude.
realOut[yWave][xWave] += (inputData[ySpace][xSpace] * cos(
2 * PI * ((1.0 * xWave * xSpace / width) + (1.0
* yWave * ySpace / height)))) / sqrt(
width * height);
imagOut[yWave][xWave] -= (inputData[ySpace][xSpace] * sin(
2 * PI * ((1.0 * xWave * xSpace / width) + (1.0
* yWave * ySpace / height)))) / sqrt(
width * height);
amplitudeOut[yWave][xWave] = sqrt(
realOut[yWave][xWave] * realOut[yWave][xWave]
+ imagOut[yWave][xWave]
* imagOut[yWave][xWave]);
}
cout << realOut[yWave][xWave] << " + " << imagOut[yWave][xWave]
<< " i (" << amplitudeOut[yWave][xWave] << ")\n";
}
}
}
}
/*
Enter the size:
2
Enter the 2D elements
2 3
4 2
2.5 + 0.0 i
5.5 + 0.0 i
-0.5 + -1.8369701987210297E-16 i
0.5 + -3.0616169978683826E-16 i
2.5 + 0.0 i
-0.5 + -3.6739403974420594E-16 i
-0.5 + -1.8369701987210297E-16 i
-1.5 + -1.8369701987210297E-16 i

View File

@ -0,0 +1,40 @@
#include<conio.h>
#include<iostream>
#include<math.h>
using namespace std;
int main(int argc, char **argv)
{
cout<<"Enter the dimension of the matrix:\n ";
int rowA;
cin>>rowA;
int colA;
cin>>colA;
cout<<"Enter the dimension of the other matrix:\n ";
int rowB;
cin>>rowB;
int colB;
cin>>colB;
if(colA == rowB)
{
cout<<"Matrices are multipilcable";
}
else
{
cout<<"Matrices are not multipilcable";
}
}
/*
Enter the dimension of the matrix:
2 4
Enter the dimension of the other matrix:
2 5
Matrices are not multipilcable
Enter the dimension of the matrix:
4 5
Enter the dimension of the other matrix:
5 6
Matrices are multipilcable

View File

@ -0,0 +1,76 @@
#include<conio.h>
#include<iostream>
#include<math.h>
using namespace std;
double d = 0;
double det(int n, double mat[10][10]);
double det(int n, double mat[10][10])
{
double submat[10][10];
if (n == 2)
return ((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
else
{
for (int c = 0; c < n; c++)
{
int subi = 0; //submatrix's i value
for (int i = 1; i < n; i++)
{
int subj = 0;
for (int j = 0; j < n; j++)
{
if (j == c)
continue;
submat[subi][subj] = mat[i][j];
subj++;
}
subi++;
}
d = d + (pow(-1, c) * mat[0][c] * det(n - 1, submat));
}
}
return d;
}
int main(int argc, char **argv)
{
cout << "Enter the dimension of the matrix:\n";
int n;
cin >> n;
double mat[10][10];
cout << "Enter the elements of the matrix:\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> mat[j][i];
}
}
if (det(n, mat) != 0)
{
cout << "The given matrix is invertible";
}
else
{
cout << "The given matrix is not invertible";
}
}
/*
Enter the dimension of the matrix:
3
Enter the elements of the matrix:
1 2 3
4 5 6
7 8 9
The given matrix is not invertible
Enter the dimension of the matrix:
5
Enter the elements of the matrix:
1 2 3 4 5
6 7 8 9 0
0 9 8 7 6
5 4 3 2 1
1 3 5 7 9
The given matrix is invertible

View File

@ -0,0 +1,54 @@
#include <iostream>
#include <conio.h>
using namespace std;
int main(int argc, char **argv)
{
cout<<"Enter the dimensions of the matrix: ";
int m, n;
cin>>m>>n;
double mat[m][n];
int zeros = 0;
cout<<"Enter the elements of the matrix: ";
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
cin>>mat[i][j];
if(mat[i][j] == 0)
{
zeros++;
}
}
}
if(zeros > (m*n)/2)
{
cout<<"The matrix is a sparse matrix";
}
else
{
cout<<"The matrix is not a sparse matrix";
}
}
/*
Enter the dimensions of the matrix:
3 3
Enter the elements of the matrix:
1 2 3
4 5 6
0 0 0
The matrix is not a sparse matrix
Enter the dimensions of the matrix:
3 3
Enter the elements of the matrix:
1 1 0
0 0 1
1 0 0
The matrix is a sparse matrix

View File

@ -0,0 +1,65 @@
/*This is a C++ Program to compute the coefficients of the DFT (Discrete Fourier Transform) directly. In mathematics, the discrete Fourier transform (DFT) converts a finite list of equally spaced samples of a function into the list of coefficients of a finite combination of complex sinusoids, ordered by their frequencies, that has those same sample values. It can be said to convert the sampled function from its original domain (often time or position along a line) to the frequency domain.*/
#include<iostream>
#include<math.h>
using namespace std;
#define PI 3.14159265
class DFT_Coefficient
{
public:
double real, img;
DFT_Coefficient()
{
real = 0.0;
img = 0.0;
}
};
int main(int argc, char **argv)
{
int N = 10;
cout << "Calculation DFT Coefficients\n";
cout << "Enter the coefficient of simple linear function:\n";
cout << "ax + by = c\n";
double a, b, c;
cin >> a >> b >> c;
double function[N];
for (int i = 0; i < N; i++)
{
function[i] = (((a * (double) i) + (b * (double) i)) - c);
//System.out.print( " "+function[i] + " ");
}
cout << "Enter the max K value: ";
int k;
cin >> k;
double cosine[N];
double sine[N];
for (int i = 0; i < N; i++)
{
cosine[i] = cos((2 * i * k * PI) / N);
sine[i] = sin((2 * i * k * PI) / N);
}
DFT_Coefficient dft_val;
cout << "The coefficients are: ";
for (int i = 0; i < N; i++)
{
dft_val.real += function[i] * cosine[i];
dft_val.img += function[i] * sine[i];
}
cout << "(" << dft_val.real << ") - " << "(" << dft_val.img << " i)";
}
/*
Calculation DFT Coefficients
Enter the coefficient of simple linear funtion:
ax + by = c
1 2 3
Enter the max K value:
2
The coefficients are: (-15) - (-20.6457 i)
------------------
(program exited with code: 0)
Press return to continue

View File

@ -0,0 +1,69 @@
#include<conio.h>
#include<iostream>
#include<math.h>
using namespace std;
double d = 0;
double det(int n, double mat[10][10]);
double det(int n, double mat[10][10])
{
double submat[10][10];
if (n == 2)
return ((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
else
{
for (int c = 0; c < n; c++)
{
int subi = 0; //submatrix's i value
for (int i = 1; i < n; i++)
{
int subj = 0;
for (int j = 0; j < n; j++)
{
if (j == c)
continue;
submat[subi][subj] = mat[i][j];
subj++;
}
subi++;
}
d = d + (pow(-1, c) * mat[0][c] * det(n - 1, submat));
}
}
return d;
}
int main(int argc, char **argv)
{
cout << "Enter the dimension of the matrix:\n";
int n;
cin >> n;
double mat[10][10];
cout << "Enter the elements of the matrix:\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> mat[j][i];
}
}
cout << "The determinant of the given matrix is: " << det(n, mat);
return 0;
}
/*
Enter the dimension of the matrix:
3
Enter the elements of the matrix:
3 5 2
8 4 8
2 4 7
The determinant of the given matrix is: -164
Enter the dimension of the matrix:
4
Enter the elements of the matrix:
9 5 2 5
9 5 3 7
6 5 4 8
1 5 3 7
The determinant of the given matrix is: 0

View File

@ -0,0 +1,84 @@
/*This is a C++ Program to perform Discrete Fourier Transform using Naive approach. In mathematics, the discrete Fourier transform (DFT) converts a finite list of equally spaced samples of a function into the list of coefficients of a finite combination of complex sinusoids, ordered by their frequencies, that has those same sample values. It can be said to convert the sampled function from its original domain (often time or position along a line) to the frequency domain.*/
#include<iostream>
#include<math.h>
using namespace std;
#define PI 3.14159265
class DFT_Coefficient
{
public:
double real, img;
DFT_Coefficient()
{
real = 0.0;
img = 0.0;
}
};
int main(int argc, char **argv)
{
int N = 10;
cout << "Discrete Fourier Transform using naive method\n";
cout << "Enter the coefficient of simple linear function:\n";
cout << "ax + by = c\n";
double a, b, c;
cin >> a >> b >> c;
double function[N];
for (int i = 0; i < N; i++)
{
function[i] = (((a * (double) i) + (b * (double) i)) - c);
//System.out.print( " "+function[i] + " ");
}
cout << "Enter the max K value: ";
int k;
cin >> k;
double cosine[N];
double sine[N];
for (int i = 0; i < N; i++)
{
cosine[i] = cos((2 * i * k * PI) / N);
sine[i] = sin((2 * i * k * PI) / N);
}
DFT_Coefficient dft_val[k];
cout << "The coefficients are: ";
for (int j = 0; j < k; j++)
{
for (int i = 0; i < N; i++)
{
dft_val[j].real += function[i] * cosine[i];
dft_val[j].img += function[i] * sine[i];
}
cout << "(" << dft_val[j].real << ") - " << "(" << dft_val[j].img << " i)\n";
}
}
/*
Discrete Fourier Transform using naive method
Enter the coefficient of simple linear function:
ax + by = c
1 2 3
Enter the max K value: 20
The coefficients are:
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)
(105) - (-1.03386e-005 i)

View File

@ -0,0 +1,73 @@
/*This is a C++ Program to perform Fast Fourier Transform. A fast Fourier transform (FFT) is an algorithm to compute the discrete Fourier transform (DFT) and its inverse. Fourier analysis converts time (or space) to frequency and vice versa; an FFT rapidly computes such transformations by factorizing the DFT matrix into a product of sparse (mostly zero) factors.*/
#include <iostream>
#include <complex>
#include <cmath>
#include <iterator>
using namespace std;
unsigned int bitReverse(unsigned int x, int log2n)
{
int n = 0;
int mask = 0x1;
for (int i = 0; i < log2n; i++)
{
n <<= 1;
n |= (x & 1);
x >>= 1;
}
return n;
}
const double PI = 3.1415926536;
template<class Iter_T>
void fft(Iter_T a, Iter_T b, int log2n)
{
typedef typename iterator_traits<iter_t>::value_type complex;
const complex J(0, 1);
int n = 1 << log2n;
for (unsigned int i = 0; i < n; ++i)
{
b[bitReverse(i, log2n)] = a[i];
}
for (int s = 1; s <= log2n; ++s)
{
int m = 1 << s;
int m2 = m >> 1;
complex w(1, 0);
complex wm = exp(-J * (PI / m2));
for (int j = 0; j < m2; ++j)
{
for (int k = j; k < n; k += m)
{
complex t = w * b[k + m2];
complex u = b[k];
b[k] = u + t;
b[k + m2] = u - t;
}
w *= wm;
}
}
}
int main(int argc, char **argv)
{
typedef complex cx;
cx a[] = { cx(0, 0), cx(1, 1), cx(3, 3), cx(4, 4), cx(4, 4), cx(3, 3), cx(
1, 1), cx(0, 0)
};
cx b[8];
fft(a, b, 3);
for (int i = 0; i < 8; ++i)
cout << b[i] << "\n";
}
/*
(16,16)
(-4.82843,-11.6569)
(0,0)
(-0.343146,0.828427)
(0,0)
(0.828427,-0.343146)
(0,0)
(-11.6569,-4.82843)

View File

@ -0,0 +1,25 @@
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
cout << "Enter the number of dice: ";
int n;
cin >> n;
cout << "The values on dice are: ( ";
for (int i = 0; i < n; i++)
cout << (rand() % 6) + 1<<" ";
cout<<")";
}
/*
Enter the number of dice: 5
The values on dice are: ( 6 6 5 5 6 )
Enter the number of dice: 1
The values on dice are: ( 6 )
Enter the number of dice: 3
The values on dice are: ( 6 6 5 )

View File

@ -0,0 +1,74 @@
#include<conio.h>
#include<iostream>
#include<math.h>
using namespace std;
double d = 0;
double det(int n, double mat[10][10]);
double det(int n, double mat[10][10])
{
double submat[10][10];
if (n == 2)
return ((mat[0][0] * mat[1][1]) - (mat[1][0] * mat[0][1]));
else
{
for (int c = 0; c < n; c++)
{
int subi = 0; //submatrix's i value
for (int i = 1; i < n; i++)
{
int subj = 0;
for (int j = 0; j < n; j++)
{
if (j == c)
continue;
submat[subi][subj] = mat[i][j];
subj++;
}
subi++;
}
d = d + (pow(-1, c) * mat[0][c] * det(n - 1, submat));
}
}
return d;
}
int main(int argc, char **argv)
{
cout << "Enter the number of vectors:\n";
int n;
cin >> n;
double mat[10][10];
cout << "Enter the vectors one by one:\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> mat[j][i];
}
}
d = det(n, mat);
if (d != 0)
cout << "The vectors forms the basis of R" << n
<< " as the determinant is non-zero";
else
cout << "The vectors doesn't form the basis of R" << n
<< " as the determinant is zero";
}
/*
Enter the number of vectors:
3
Enter the vectors one by one:
1 2 3
2 3 4
3 4 5
The vectors doesn't form the basis of R3 as the determinant is zero
Enter the number of vectors:
4
Enter the vectors one by one:
2 3 5 8
1 6 2 9
3 4 2 7
2 5 3 9
The vectors forms the basis of R4 as the determinant is non-zero

View File

@ -0,0 +1,137 @@
/*
* C++ Program to Find Closest Pair of Points in an Array
*/
#include <iostream>
#include <cfloat>
#include <cstdlib>
#include <cmath>
using namespace std;
/*
* Point Declaration
*/
struct Point
{
int x, y;
};
/*
* sort array of points according to X coordinate
*/
int compareX(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->x - p2->x);
}
/*
* sort array of points according to Y coordinate
*/
int compareY(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->y - p2->y);
}
/*
* find the distance between two points
*/
float dist(Point p1, Point p2)
{
return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
/*
* return the smallest distance between two points
*/
float small_dist(Point P[], int n)
{
float min = FLT_MAX;
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (dist(P[i], P[j]) < min)
min = dist(P[i], P[j]);
}
}
return min;
}
/*
* find the distance beween the closest points of strip of given size
*/
float stripClosest(Point strip[], int size, float d)
{
float min = d;
for (int i = 0; i < size; ++i)
{
for (int j = i + 1; j < size && (strip[j].y - strip[i].y) < min; ++j)
{
if (dist(strip[i],strip[j]) < min)
min = dist(strip[i], strip[j]);
}
}
return min;
}
/*
* find the smallest distance.
*/
float closestUtil(Point Px[], Point Py[], int n)
{
if (n <= 3)
return small_dist(Px, n);
int mid = n / 2;
Point midPoint = Px[mid];
Point Pyl[mid + 1];
Point Pyr[n - mid - 1];
int li = 0, ri = 0;
for (int i = 0; i < n; i++)
{
if (Py[i].x <= midPoint.x)
Pyl[li++] = Py[i];
else
Pyr[ri++] = Py[i];
}
float dl = closestUtil(Px, Pyl, mid);
float dr = closestUtil(Px + mid, Pyr, n-mid);
float d = min(dl, dr);
Point strip[n];
int j = 0;
for (int i = 0; i < n; i++)
{
if (abs(Py[i].x - midPoint.x) < d)
strip[j] = Py[i], j++;
}
return min(d, stripClosest(strip, j, d));
}
/*
* finds the smallest distance
*/
float closest(Point P[], int n)
{
Point Px[n];
Point Py[n];
for (int i = 0; i < n; i++)
{
Px[i] = P[i];
Py[i] = P[i];
}
qsort(Px, n, sizeof(Point), compareX);
qsort(Py, n, sizeof(Point), compareY);
return closestUtil(Px, Py, n);
}
/*
* Main
*/
int main()
{
Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}};
int n = sizeof(P) / sizeof(P[0]);
cout << "The smallest distance is " << closest(P, n);
return 0;
}
/*
The smallest distance is 1.41421
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,83 @@
/*
* C++ Program to Find Factorial of Large Numbers
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
int fact[101][200] = {0};
/*
* Find Factorial of Large Numbers
* fact[i][0] is used to store the number of digits
*/
void fact_large(int n)
{
int i;
fact[1][0] = 1;
fact[1][1] = 1;
if (fact[n][0] == 0)
{
for (i = n - 1; i > 0 ; i--)
{
if (fact[i][0] != 0)
break;
}
for ( ; i < n; i++)
{
int j = 1;
int carry = 0;
int len = fact[i][0];
while (len--)
{
int temp = (i + 1) * fact[i][j] + carry;
fact[i + 1][j] = temp % 10;
carry = temp / 10;
j++;
}
while (carry > 0)
{
fact[i + 1][j] = carry % 10;
carry /= 10;
j++;
}
fact[i + 1][0] = j - 1;
}
}
for (i = fact[n][0]; i > 0; i--)
{
cout << fact[n][i];
}
cout<<endl;
}
/*
* Main
*/
int main()
{
int n;
while (1)
{
cout<<"Enter interger to compute factorial(0 to exit): ";
cin>>n;
if (n == 0)
break;
fact_large(n);
}
return 0;
}
/*
Enter interger to compute factorial(0 to exit): 100
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Enter interger to compute factorial(0 to exit): 50
30414093201713378043612608166064768844377641568960512000000000000
Enter interger to compute factorial(0 to exit): 72
61234458376886086861524070385274672740778091784697328983823014963978384987221689274204160000000000000000
Enter interger to compute factorial(0 to exit): 0
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,55 @@
/*
* C++ Program to Find Factorial of a Number using Dynamic Programming
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
int result[1000] = {0};
/*
* Find Factorial of a Number using Dynamic Programming
*/
ll fact_dp(int n)
{
if (n >= 0)
{
result[0] = 1;
for (int i = 1; i <= n; ++i)
{
result[i] = i * result[i - 1];
}
return result[n];
}
}
/*
* Main
*/
int main()
{
int n;
while (1)
{
cout<<"Enter interger to compute factorial(0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fact_dp(n)<<endl;
}
return 0;
}
/*
Enter interger to compute factorial(0 to exit): 10
3628800
Enter interger to compute factorial(0 to exit): 20
2432902008176640000
Enter interger to compute factorial(0 to exit): 15
1307674368000
Enter interger to compute factorial(0 to exit): 0
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,49 @@
/*
* C++ Program to Find Factorial of a Number using Iteration
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
/*
* Find Factorial of a Number using Iteration
*/
ll fact_iter(int n)
{
ll result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
/*
* Main
*/
int main()
{
int n;
while (1)
{
cout<<"Enter interger to compute factorial(0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fact_iter(n)<<endl;
}
return 0;
}
/*
Enter interger to compute factorial(0 to exit): 10
3628800
Enter interger to compute factorial(0 to exit): 20
2432902008176640000
Enter interger to compute factorial(0 to exit): 15
1307674368000
Enter interger to compute factorial(0 to exit): 0
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,47 @@
/*
* C++ Program to Find Factorial of a Number using Recursion
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
/*
* Find Factorial of a Number using Recursion
*/
ll fact_recur(int n)
{
if (n == 0 || n == 1)
return 1;
else
return n * fact_recur(n - 1);
}
/*
* Main
*/
int main()
{
int n;
while (1)
{
cout<<"Enter interger to compute factorial(0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fact_recur(n)<<endl;
}
return 0;
}
/*
Enter interger to compute factorial(0 to exit): 10
3628800
Enter interger to compute factorial(0 to exit): 20
2432902008176640000
Enter interger to compute factorial(0 to exit): 15
1307674368000
Enter interger to compute factorial(0 to exit): 0
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,71 @@
/*
* C++ Program to Find Fibonacci Numbers using Dynamic Programming
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
ll fib[1000] = {0};
/*
* Fibonacci Numbers using Dp
*/
ll fibo_dp(int n)
{
fib[1] = 1;
fib[2] = 1;
if (fib[n] == 0)
{
for (int j = 3; j <= n; ++j)
{
if (fib[n] == 0)
fib[j] = fib[j - 1] + fib[j - 2];
else
continue;
}
}
return fib[n];
}
/*
* Main
*/
int main()
{
int n;
while (1)
{
cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fibo_dp(n)<<endl;
}
return 0;
}
/*
Enter the integer n to find nth fibonnaci no.(0 to exit): 10
55
Enter the integer n to find nth fibonnaci no.(0 to exit): 9
34
Enter the integer n to find nth fibonnaci no.(0 to exit): 8
21
Enter the integer n to find nth fibonnaci no.(0 to exit): 7
13
Enter the integer n to find nth fibonnaci no.(0 to exit): 6
8
Enter the integer n to find nth fibonnaci no.(0 to exit): 5
5
Enter the integer n to find nth fibonnaci no.(0 to exit): 4
3
Enter the integer n to find nth fibonnaci no.(0 to exit): 3
2
Enter the integer n to find nth fibonnaci no.(0 to exit): 2
1
Enter the integer n to find nth fibonnaci no.(0 to exit): 0
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,68 @@
/*
* C++ Program to Find Fibonacci Numbers using Iteration
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
/*
* Iterative function to find Fibonacci Numbers
*/
ll fibo_iter(int n)
{
int previous = 1;
int current = 1;
int next = 1;
for (int i = 3; i <= n; ++i)
{
next = current + previous;
previous = current;
current = next;
}
return next;
}
/*
* Main
*/
int main()
{
int n;
while (1)
{
cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fibo_iter(n)<<endl;
}
return 0;
}
/*
Enter the integer n to find nth fibonnaci no.(0 to exit): 1
1
Enter the integer n to find nth fibonnaci no.(0 to exit): 2
1
Enter the integer n to find nth fibonnaci no.(0 to exit): 3
2
Enter the integer n to find nth fibonnaci no.(0 to exit): 4
3
Enter the integer n to find nth fibonnaci no.(0 to exit): 5
5
Enter the integer n to find nth fibonnaci no.(0 to exit): 6
8
Enter the integer n to find nth fibonnaci no.(0 to exit): 7
13
Enter the integer n to find nth fibonnaci no.(0 to exit): 8
21
Enter the integer n to find nth fibonnaci no.(0 to exit): 9
34
Enter the integer n to find nth fibonnaci no.(0 to exit): 10
55
Enter the integer n to find nth fibonnaci no.(0 to exit): 0
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,92 @@
/*
* C++ Program to Find Fibonacci Numbers using Matrix Exponentiation
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
/*
* function to multiply two matrices
*/
void multiply(ll F[2][2], ll M[2][2])
{
ll x = F[0][0] * M[0][0] + F[0][1] * M[1][0];
ll y = F[0][0] * M[0][1] + F[0][1] * M[1][1];
ll z = F[1][0] * M[0][0] + F[1][1] * M[1][0];
ll w = F[1][0] * M[0][1] + F[1][1] * M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
/*
* function to calculate power of a matrix
*/
void power(ll F[2][2], int n)
{
if (n == 0 || n == 1)
return;
ll M[2][2] = {{1,1},{1,0}};
power(F, n / 2);
multiply(F, F);
if (n % 2 != 0)
multiply(F, M);
}
/*
* function that returns nth Fibonacci number
*/
ll fibo_matrix(ll n)
{
ll F[2][2] = {{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n - 1);
return F[0][0];
}
/*
* Main
*/
int main()
{
int n;
while (1)
{
cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fibo_matrix(n)<<endl;
}
return 0;
}
/*
Enter the integer n to find nth fibonnaci no.(0 to exit): 1
1
Enter the integer n to find nth fibonnaci no.(0 to exit): 2
1
Enter the integer n to find nth fibonnaci no.(0 to exit): 3
2
Enter the integer n to find nth fibonnaci no.(0 to exit): 4
3
Enter the integer n to find nth fibonnaci no.(0 to exit): 5
5
Enter the integer n to find nth fibonnaci no.(0 to exit): 6
8
Enter the integer n to find nth fibonnaci no.(0 to exit): 7
13
Enter the integer n to find nth fibonnaci no.(0 to exit): 8
21
Enter the integer n to find nth fibonnaci no.(0 to exit): 9
34
Enter the integer n to find nth fibonnaci no.(0 to exit): 10
55
Enter the integer n to find nth fibonnaci no.(0 to exit): 0
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,62 @@
/*
* C++ Program to Find Fibonacci Numbers using Recursion
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
/*
* Recursive function to find Fibonnaci Numbers
*/
ll fibo_recur(int n)
{
if (n == 1 || n == 2)
return 1;
else
return fibo_recur(n - 1) + fibo_recur(n - 2);;
}
/*
* Main
*/
int main()
{
int n;
while (1)
{
cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fibo_recur(n)<<endl;
}
return 0;
}
/*
Enter the integer n to find nth fibonnaci no.(0 to exit): 1
1
Enter the integer n to find nth fibonnaci no.(0 to exit): 2
1
Enter the integer n to find nth fibonnaci no.(0 to exit): 3
2
Enter the integer n to find nth fibonnaci no.(0 to exit): 4
3
Enter the integer n to find nth fibonnaci no.(0 to exit): 5
5
Enter the integer n to find nth fibonnaci no.(0 to exit): 6
8
Enter the integer n to find nth fibonnaci no.(0 to exit): 7
13
Enter the integer n to find nth fibonnaci no.(0 to exit): 8
21
Enter the integer n to find nth fibonnaci no.(0 to exit): 9
34
Enter the integer n to find nth fibonnaci no.(0 to exit): 10
55
Enter the integer n to find nth fibonnaci no.(0 to exit): 0
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,35 @@
/*This is a C++ Program to find GCD of two numbers using Recursive Euclid Algorithm. In mathematics, the Euclidean algorithm, or Euclids algorithm, is a method for computing the greatest common divisor (GCD) of two (usually positive) integers, also known as the greatest common factor (GCF) or highest common factor (HCF). It is named after the Greek mathematician Euclid, who described it in Books VII and X of his Elements.
The GCD of two positive integers is the largest integer that divides both of them without leaving a remainder (the GCD of two integers in general is defined in a more subtle way).
In its simplest form, Euclids algorithm starts with a pair of positive integers, and forms a new pair that consists of the smaller number and the difference between the larger and smaller numbers. The process repeats until the numbers in the pair are equal. That number then is the greatest common divisor of the original pair of integers.
The main principle is that the GCD does not change if the smaller number is subtracted from the larger number. For example, the GCD of 252 and 105 is exactly the GCD of 147 (= 252 105) and 105. Since the larger of the two numbers is reduced, repeating this process gives successively smaller numbers, so this repetition will necessarily stop sooner or later when the numbers are equal (if the process is attempted once more, one of the numbers will become 0).*/
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int gcd(int u, int v)
{
return (v != 0) ? gcd(v, u % v) : u;
}
int main(void)
{
int num1, num2, result;
cout << "Enter two numbers to find GCD using Euclidean algorithm: ";
cin >> num1 >> num2;
result = gcd(num1, num2);
if (gcd)
cout << "\nThe GCD of " << num1 << " and " << num2 << " is: " << result
<< endl;
else
cout << "\nInvalid input!!!\n";
return 0;
}
/*
Enter two numbers to find GCD using Euclidean algorithm: 12 30
The GCD of 12 and 30 is: 6

View File

@ -0,0 +1,565 @@
#if !defined(MATRIX_H)
#define MATRIX_H
#include <stdio.h>
#include <iostream>
#include <tchar.h>
#include <math.h>
#include <stdlib.h>
class CMatrix
{
private:
int m_rows;
int m_cols;
char m_name[128];
CMatrix();
public:
double **m_pData;
CMatrix(const char *name, int rows, int cols) :
m_rows(rows), m_cols(cols)
{
strcpy(m_name, name);
m_pData = new double*[m_rows];
for (int i = 0; i < m_rows; i++)
m_pData[i] = new double[m_cols];
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
m_pData[i][j] = 0.0;
}
}
}
CMatrix(const CMatrix &other)
{
strcpy(m_name, other.m_name);
m_rows = other.m_rows;
m_cols = other.m_cols;
m_pData = new double*[m_rows];
for (int i = 0; i < m_rows; i++)
m_pData[i] = new double[m_cols];
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
m_pData[i][j] = other.m_pData[i][j];
}
}
}
~CMatrix()
{
for (int i = 0; i < m_rows; i++)
delete[] m_pData[i];
delete[] m_pData;
m_rows = m_cols = 0;
}
void SetName(const char *name)
{
strcpy(m_name, name);
}
const char* GetName() const
{
return m_name;
}
void GetInput()
{
std::cin >> *this;
}
void FillSimulatedInput()
{
static int factor1 = 1, factor2 = 2;
std::cout << "\n\nEnter Input For Matrix : " << m_name << " Rows: "
<< m_rows << " Cols: " << m_cols << "\n";
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
std::cout << "Input For Row: " << i + 1 << " Col: " << j
+ 1 << " = ";
int data = ((i + 1) * factor1) + (j + 1) * factor2;
m_pData[i][j] = data / 10.2;
std::cout << m_pData[i][j] << "\n";
factor1 += (rand() % 4);
factor2 += (rand() % 3);
}
std::cout << "\n";
}
std::cout << "\n";
}
double Determinant()
{
double det = 0;
double **pd = m_pData;
switch (m_rows)
{
case 2:
{
det = pd[0][0] * pd[1][1] - pd[0][1] * pd[1][0];
return det;
}
break;
case 3:
{
/***
a b c
d e f
g h i
a b c a b c
d e f d e f
g h i g h i
// det (A) = aei + bfg + cdh - afh - bdi - ceg.
***/
double a = pd[0][0];
double b = pd[0][1];
double c = pd[0][2];
double d = pd[1][0];
double e = pd[1][1];
double f = pd[1][2];
double g = pd[2][0];
double h = pd[2][1];
double i = pd[2][2];
double det = (a * e * i + b * f * g + c * d * h);
det = det - a * f * h;
det = det - b * d * i;
det = det - c * e * g;
return det;
}
break;
case 4:
{
CMatrix *temp[4];
for (int i = 0; i < 4; i++)
temp[i] = new CMatrix("", 3, 3);
for (int k = 0; k < 4; k++)
{
for (int i = 1; i < 4; i++)
{
int j1 = 0;
for (int j = 0; j < 4; j++)
{
if (k == j)
continue;
temp[k]->m_pData[i - 1][j1++]
= this->m_pData[i][j];
}
}
}
double det = this->m_pData[0][0] * temp[0]->Determinant()
- this->m_pData[0][1] * temp[1]->Determinant()
+ this->m_pData[0][2] * temp[2]->Determinant()
- this->m_pData[0][3] * temp[3]->Determinant();
return det;
}
break;
case 5:
{
CMatrix *temp[5];
for (int i = 0; i < 5; i++)
temp[i] = new CMatrix("", 4, 4);
for (int k = 0; k < 5; k++)
{
for (int i = 1; i < 5; i++)
{
int j1 = 0;
for (int j = 0; j < 5; j++)
{
if (k == j)
continue;
temp[k]->m_pData[i - 1][j1++]
= this->m_pData[i][j];
}
}
}
double det = this->m_pData[0][0] * temp[0]->Determinant()
- this->m_pData[0][1] * temp[1]->Determinant()
+ this->m_pData[0][2] * temp[2]->Determinant()
- this->m_pData[0][3] * temp[3]->Determinant()
+ this->m_pData[0][4] * temp[4]->Determinant();
return det;
}
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
default:
{
int DIM = m_rows;
CMatrix **temp = new CMatrix*[DIM];
for (int i = 0; i < DIM; i++)
temp[i] = new CMatrix("", DIM - 1, DIM - 1);
for (int k = 0; k < DIM; k++)
{
for (int i = 1; i < DIM; i++)
{
int j1 = 0;
for (int j = 0; j < DIM; j++)
{
if (k == j)
continue;
temp[k]->m_pData[i - 1][j1++]
= this->m_pData[i][j];
}
}
}
double det = 0;
for (int k = 0; k < DIM; k++)
{
if ((k % 2) == 0)
det = det + (this->m_pData[0][k]
* temp[k]->Determinant());
else
det = det - (this->m_pData[0][k]
* temp[k]->Determinant());
}
for (int i = 0; i < DIM; i++)
delete temp[i];
delete[] temp;
return det;
}
break;
}
}
CMatrix& operator =(const CMatrix &other)
{
if (this->m_rows != other.m_rows || this->m_cols != other.m_cols)
{
std::cout
<< "WARNING: Assignment is taking place with by changing the number of rows and columns of the matrix";
}
for (int i = 0; i < m_rows; i++)
delete[] m_pData[i];
delete[] m_pData;
m_rows = m_cols = 0;
strcpy(m_name, other.m_name);
m_rows = other.m_rows;
m_cols = other.m_cols;
m_pData = new double*[m_rows];
for (int i = 0; i < m_rows; i++)
m_pData[i] = new double[m_cols];
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
m_pData[i][j] = other.m_pData[i][j];
}
}
return *this;
}
CMatrix CoFactor()
{
CMatrix cofactor("COF", m_rows, m_cols);
if (m_rows != m_cols)
return cofactor;
if (m_rows < 2)
return cofactor;
else if (m_rows == 2)
{
cofactor.m_pData[0][0] = m_pData[1][1];
cofactor.m_pData[0][1] = -m_pData[1][0];
cofactor.m_pData[1][0] = -m_pData[0][1];
cofactor.m_pData[1][1] = m_pData[0][0];
return cofactor;
}
else if (m_rows >= 3)
{
int DIM = m_rows;
CMatrix ***temp = new CMatrix**[DIM];
for (int i = 0; i < DIM; i++)
temp[i] = new CMatrix*[DIM];
for (int i = 0; i < DIM; i++)
for (int j = 0; j < DIM; j++)
temp[i][j] = new CMatrix("", DIM - 1, DIM - 1);
for (int k1 = 0; k1 < DIM; k1++)
{
for (int k2 = 0; k2 < DIM; k2++)
{
int i1 = 0;
for (int i = 0; i < DIM; i++)
{
int j1 = 0;
for (int j = 0; j < DIM; j++)
{
if (k1 == i || k2 == j)
continue;
temp[k1][k2]->m_pData[i1][j1++]
= this->m_pData[i][j];
}
if (k1 != i)
i1++;
}
}
}
bool flagPositive = true;
for (int k1 = 0; k1 < DIM; k1++)
{
flagPositive = ((k1 % 2) == 0);
for (int k2 = 0; k2 < DIM; k2++)
{
if (flagPositive == true)
{
cofactor.m_pData[k1][k2]
= temp[k1][k2]->Determinant();
flagPositive = false;
}
else
{
cofactor.m_pData[k1][k2]
= -temp[k1][k2]->Determinant();
flagPositive = true;
}
}
}
for (int i = 0; i < DIM; i++)
for (int j = 0; j < DIM; j++)
delete temp[i][j];
for (int i = 0; i < DIM; i++)
delete[] temp[i];
delete[] temp;
}
return cofactor;
}
CMatrix Adjoint()
{
CMatrix cofactor("COF", m_rows, m_cols);
CMatrix adj("ADJ", m_rows, m_cols);
if (m_rows != m_cols)
return adj;
cofactor = this->CoFactor();
// adjoint is transpose of a cofactor of a matrix
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
adj.m_pData[j][i] = cofactor.m_pData[i][j];
}
}
return adj;
}
CMatrix Transpose()
{
CMatrix trans("TR", m_cols, m_rows);
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
trans.m_pData[j][i] = m_pData[i][j];
}
}
return trans;
}
CMatrix Inverse()
{
CMatrix cofactor("COF", m_rows, m_cols);
CMatrix inv("INV", m_rows, m_cols);
if (m_rows != m_cols)
return inv;
// to find out Determinant
double det = Determinant();
cofactor = this->CoFactor();
// inv = transpose of cofactor / Determinant
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
inv.m_pData[j][i] = cofactor.m_pData[i][j] / det;
}
}
return inv;
}
CMatrix operator +(const CMatrix &other)
{
if (this->m_rows != other.m_rows || this->m_cols != other.m_cols)
{
std::cout
<< "Addition could not take place because number of rows and columns are different between the two matrices";
return *this;
}
CMatrix result("", m_rows, m_cols);
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
result.m_pData[i][j] = this->m_pData[i][j]
+ other.m_pData[i][j];
}
}
return result;
}
CMatrix operator -(const CMatrix &other)
{
if (this->m_rows != other.m_rows || this->m_cols != other.m_cols)
{
std::cout
<< "Subtraction could not take place because number of rows and columns are different between the two matrices";
return *this;
}
CMatrix result("", m_rows, m_cols);
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
result.m_pData[i][j] = this->m_pData[i][j]
- other.m_pData[i][j];
}
}
return result;
}
CMatrix operator *(const CMatrix &other)
{
if (this->m_cols != other.m_rows)
{
std::cout
<< "Multiplication could not take place because number of columns of 1st Matrix and number of rows in 2nd Matrix are different";
return *this;
}
CMatrix result("", this->m_rows, other.m_cols);
for (int i = 0; i < this->m_rows; i++)
{
for (int j = 0; j < other.m_cols; j++)
{
for (int k = 0; k < this->m_cols; k++)
{
result.m_pData[i][j] += this->m_pData[i][k]
* other.m_pData[k][j];
}
}
}
return result;
}
bool operator ==(const CMatrix &other)
{
if (this->m_rows != other.m_rows || this->m_cols != other.m_cols)
{
std::cout
<< "Comparision could not take place because number of rows and columns are different between the two matrices";
return false;
}
CMatrix result("", m_rows, m_cols);
bool bEqual = true;
for (int i = 0; i < m_rows; i++)
{
for (int j = 0; j < m_cols; j++)
{
if (this->m_pData[i][j] != other.m_pData[i][j])
bEqual = false;
}
}
return bEqual;
}
friend std::istream& operator >>(std::istream &is, CMatrix &m);
friend std::ostream& operator <<(std::ostream &os, const CMatrix &m);
};
std::istream& operator >>(std::istream &is, CMatrix &m)
{
std::cout << "\n\nEnter Input For Matrix : " << m.m_name << " Rows: "
<< m.m_rows << " Cols: " << m.m_cols << "\n";
for (int i = 0; i < m.m_rows; i++)
{
for (int j = 0; j < m.m_cols; j++)
{
std::cout << "Input For Row: " << i + 1 << " Col: " << j + 1
<< " = ";
is >> m.m_pData[i][j];
}
std::cout << "\n";
}
std::cout << "\n";
return is;
}
std::ostream& operator <<(std::ostream &os, const CMatrix &m)
{
os << "\n\nMatrix : " << m.m_name << " Rows: " << m.m_rows << " Cols: "
<< m.m_cols << "\n\n";
for (int i = 0; i < m.m_rows; i++)
{
os << " | ";
for (int j = 0; j < m.m_cols; j++)
{
char buf[32];
double data = m.m_pData[i][j];
if (m.m_pData[i][j] > -0.00001 && m.m_pData[i][j] < 0.00001)
data = 0;
sprintf(buf, "%10.2lf ", data);
os << buf;
}
os << "|\n";
}
os << "\n\n";
return os;
}
#endif
int main()
{
CMatrix a("A", 5, 5);
//std::cin >> a;
a.FillSimulatedInput();
CMatrix aadj = a.Inverse();
std::cout << a;
std::cout << aadj;
CMatrix unit = (a * aadj);
unit.SetName("A * A-Inv");
std::cout << unit;
}
/*
Enter Input For Matrix :
A Rows: 5
Cols: 5
Input For Row: 1 Col: 1 = 0.294118
Input For Row: 1 Col: 2 = 0.980392
Input For Row: 1 Col: 3 = 1.86275
Input For Row: 1 Col: 4 = 2.84314
Input For Row: 1 Col: 5 = 3.62745
Input For Row: 2 Col: 1 = 2.54902
Input For Row: 2 Col: 2 = 3.92157
Input For Row: 2 Col: 3 = 5.09804
Input For Row: 2 Col: 4 = 7.05882
Input For Row: 2 Col: 5 = 9.80392
Input For Row: 3 Col: 1 = 6.66667
Input For Row: 3 Col: 2 = 8.92157
Input For Row: 3 Col: 3 = 10.8824
Input For Row: 3 Col: 4 = 12.6471
Input For Row: 3 Col: 5 = 15.3922
Input For Row: 4 Col: 1 = 12.0588
Input For Row: 4 Col: 2 = 15.098
Input For Row: 4 Col: 3 = 18.1373
Input For Row: 4 Col: 4 = 20.7843
Input For Row: 4 Col: 5 = 24.4118
Input For Row: 5 Col: 1 = 21.1765
Input For Row: 5 Col: 2 = 24.7059
Input For Row: 5 Col: 3 = 27.7451
Input For Row: 5 Col: 4 = 31.0784
Input For Row: 5 Col: 5 = 34.3137
Matrix : A Rows: 5 Cols: 5
| 0.29 0.98 1.86 2.84 3.63 |
| 2.55 3.92 5.10 7.06 9.80 |
| 6.67 8.92 10.88 12.65 15.39 |
| 12.06 15.10 18.14 20.78 24.41 |
| 21.18 24.71 27.75 31.08 34.31 |
Matrix : INV Rows: 5 Cols: 5
| -0.93 0.80 -3.74 2.86 -0.49 |
| 0.37 -0.32 5.35 -4.91 1.14 |
| -0.78 -0.93 -1.46 2.96 -1.10 |
| 2.37 -0.10 0.25 -1.65 0.84 |
| -1.21 0.57 -0.58 0.87 -0.36 |
Matrix : A * A-Inv Rows: 5 Cols: 5
| 1.00 0.00 0.00 0.00 0.00 |
| 0.00 1.00 0.00 0.00 0.00 |
| 0.00 0.00 1.00 0.00 0.00 |
| 0.00 0.00 0.00 1.00 0.00 |
| 0.00 0.00 0.00 0.00 1.00 |

View File

@ -0,0 +1,109 @@
#include <iostream>
#include <list>
using namespace std;
// This class represents a directed graph using adjacency list representation
class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
bool isReachable(int s, int d); // returns true if there is a path from s to d
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int> [V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to vs list.
}
// A BFS based function to check whether d is reachable from s.
bool Graph::isReachable(int s, int d)
{
// Base case
if (s == d)
return true;
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// it will be used to get all adjacent vertices of a vertex
list<int>::iterator i;
while (!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
queue.pop_front();
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it visited
// and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
// If this adjacent node is the destination node, then return true
if (*i == d)
return true;
// Else, continue to do BFS
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
return false;
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Enter the source and destination vertices: (0-3)";
int u, v;
cin >> u >> v;
if (g.isReachable(u, v))
cout << "\nThere is a path from " << u << " to " << v;
else
cout << "\nThere is no path from " << u << " to " << v;
int temp;
temp = u;
u = v;
v = temp;
if (g.isReachable(u, v))
cout << "\nThere is a path from " << u << " to " << v;
else
cout << "\nThere is no path from " << u << " to " << v;
return 0;
}
/*
Enter the source and destination vertices: (0-3)
1 3
There is a path from 1 to 3
There is no path from 3 to 1
Enter the source and destination vertices: (0-3)
2 3
There is a path from 2 to 3
There is no path from 3 to 2

View File

@ -0,0 +1,57 @@
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int gcd(int x, int y)
{
int r = 0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while (a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
int lcm(int x, int y)
{
int a;
a = (x > y) ? x : y; // a is greater number
while (true)
{
if (a % x == 0 && a % y == 0)
return a;
++a;
}
}
int main(int argc, char **argv)
{
cout << "Enter the two numbers: ";
int x, y;
cin >> x >> y;
cout << "The GCD of two numbers is: " << gcd(x, y) << endl;
;
cout << "The LCM of two numbers is: " << lcm(x, y) << endl;
;
return 0;
}
/*
Enter the two numbers:
5
8
The GCD of two numbers is: 1
The LCM of two numbers is: 40
Enter the two numbers:
100
50
The GCD of two numbers is: 50
The LCM of two numbers is: 100

View File

@ -0,0 +1,179 @@
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void permute(int *a, int k, int size)
{
if (k == size)
{
for (int i = 0; i < size; i++)
{
cout << *(a + i);
}
cout << endl;
}
else
{
for (int i = k; i < size; i++)
{
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1, size);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
int main(int argc, char **argv)
{
cout << "Enter the length of the password: ";
int m;
cin >> m;
int a[m];
for (int i = 0; i < m; i++)
{
/*generates random number between 1 and 10*/
a[i] = rand() % 10;
}
for (int i = 0; i < m; i++)
{
cout << a[i] << ", ";
}
cout << "The Passwords are: ";
permute(a, 0, m);
}
/*
Enter the length of the password: 3
1, 7, 4, The Passwords are: 174
147
714
741
471
417
Enter the length of the password: 5
1, 7, 4, 0, 9, The Passwords are: 17409
17490
17049
17094
17904
17940
14709
14790
14079
14097
14907
14970
10479
10497
10749
10794
10974
10947
19407
19470
19047
19074
19704
19740
71409
71490
71049
71094
71904
71940
74109
74190
74019
74091
74901
74910
70419
70491
70149
70194
70914
70941
79401
79410
79041
79014
79104
79140
47109
47190
47019
47091
47901
47910
41709
41790
41079
41097
41907
41970
40179
40197
40719
40791
40971
40917
49107
49170
49017
49071
49701
49710
07419
07491
07149
07194
07914
07941
04719
04791
04179
04197
04917
04971
01479
01497
01749
01794
01974
01947
09417
09471
09147
09174
09714
09741
97401
97410
97041
97014
97104
97140
94701
94710
94071
94017
94107
94170
90471
90417
90741
90714
90174
90147
91407
91470
91047
91074
91704
91740

View File

@ -0,0 +1,72 @@
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome to the Sieve of Sundaram\n" << endl;
int arraySize;
int numberPrimes = 0;
cout << "Input a positive integer to find all the prime numbers up to and "
<< "\nincluding that number: ";
cin >> arraySize;
int n = arraySize / 2;
/* array to start off with that will eventually get
all the composite numbers removed and the remaining
ones output to the screen */
int isPrime[arraySize + 1];
for (int i = 0; i < n; ++i)
{
isPrime[i] = i;
}
for (int i = 1; i < n; i++)
{
for (int j = i; j <= (n - i) / (2 * i + 1); j++)
{
isPrime[i + j + 2 * i * j] = 0;/*From this list, remove all
numbers of the form i + j + 2ij */
}
}
int TheseArePrime = 0;
if (arraySize > 2)
{
isPrime[TheseArePrime++] = 2;/*this IF statement adds 2 to the output */
}
for (int i = 1; i < n; i++)
{
if (isPrime[i] != 0)
{
isPrime[TheseArePrime++] = i * 2 + 1;
}
}
int size = sizeof isPrime / sizeof(int);//total size of array/size of array data type
for (int x = 0; x <= size; x++)
{
if (isPrime[x] != 0)
{
cout << isPrime[x] << "\t";//outputs all prime numbers found
numberPrimes++;// the counter of the number of primes found
}
else
{
break;
}
}
cout << "\nNumber of Primes: " << numberPrimes << endl;
return 0;
}
/*
Welcome to the Sieve of Sundaram
Input a positive integer to find all the prime numbers up to and
including that number: 10
2 3 5 7
Number of Primes: 4
Welcome to the Sieve of Sundaram
Input a positive integer to find all the prime numbers up to and
including that number: 100
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
Number of Primes: 25

View File

@ -0,0 +1,18 @@
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
int val = rand();
char Hex[33];
itoa(val, Hex, 16);
cout<< "Random Decimal Byte:" << val;
cout << "\nEquivalent Hex Byte: " << Hex;
}
/*
Random Decimal Byte:41
Equivalent Hex Byte: 29

View File

@ -0,0 +1,45 @@
/*This is a C++ Program to generate random numbers using Middle Square method. In mathematics, the middle-square method is a method of generating pseudorandom numbers. In practice it is not a good method, since its period is usually very short and it has some severe weaknesses, such as the output sequence almost always converging to zero.*/
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
int a[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
int middleSquareNumber(int numb, int dig)
{
int sqn = numb * numb, next_num = 0;
int trim = (dig / 2);
sqn = sqn / a[trim];
for (int i = 0; i < dig; i++)
{
next_num += (sqn % (a[trim])) * (a[i]);
sqn = sqn / 10;
}
return next_num;
}
int main(int argc, char **argv)
{
cout << "Enter the #-digit random numbers you want: ";
int n;
cin >> n;
int start = 1, end = 1;
start = a[n - 1];
end = a[n];
int number = ((rand()) % (end - start)) + start;
cout << "The random numbers are:\n" << number << ", ";
for (int i = 1; i < n; i++)
{
number = middleSquareNumber(number, n);
cout << number << ", ";
}
cout << "...";
}
/*
Enter the #-digit random numbers you want: 5
The random numbers are:
10041, 16426, 796264, -276041, -115546, ...

View File

@ -0,0 +1,31 @@
/*This is a C++ Program to generate random numbers using Multiply with Carry method. In computer science, multiply-with-carry (MWC) is a method invented by George Marsaglia for generating sequences of random integers based on an initial set from two to many thousands of randomly chosen seed values. The main advantages of the MWC method are that it invokes simple computer integer arithmetic and leads to very fast generation of sequences of random numbers with immense periods, ranging from around 260 to 22000000.*/
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
int max_Sequence_Elements = 10;
int base_b = 2000;
int multiplier_a = rand() % base_b;
int r = 1;
int c[max_Sequence_Elements];
int x[max_Sequence_Elements];
c[0] = rand() % multiplier_a;
x[0] = rand() % base_b;
cout << "The random number sequence is: " << x[0];
//generating sequence
for (int i = 1; i < max_Sequence_Elements; i++)
{
x[i] = (multiplier_a * x[i - r] + c[i - 1]) % base_b;
c[i] = (multiplier_a * x[i - r] + c[i - 1]) / base_b;
cout << " " << x[i];
}
cout << "...";
}
/*
The random number sequence is: 334 1711 157 472 1355 1564 151 223 1146 990...

View File

@ -0,0 +1,34 @@
/*This is a C++ Program to generate random numbers using Probability Distribution Function. Probability distribution is based on probability density function. a probability density function (pdf), or density of a continuous random variable, is a function that describes the relative likelihood for this random variable to take on a given value. The probability of the random variable falling within a particular range of values is given by the integral of this variables density over that range—that is, it is given by the area under the density function but above the horizontal axis and between the lowest and greatest values of the range.*/
//pdf(x) = 1 if x>360
// = 0 if x<0
// = x/360 otherwise
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
//This is a sample program to generate a random numbers based on probability desity function of spiner
//pdf(x) = 1 if x>360
// = 0 if x<0
// = x/360 otherwise
int N = 10;
int main(int argc, char **argv)
{
int p = 0;
for (int i = 0; i < N; i++)
{
p = rand() % 400;
if (p > 360)
cout << 0 << " ";
else if (p < 0)
cout << 0 << " ";
else
cout << p * 0.1 / 360 << " ";
}
cout << "...";
}
/*
0.0113889 0.0186111 0.0927778 0.0277778 0 0.0344444 0.0772222 0.0438889 0.045 0.0177778 ...

View File

@ -0,0 +1,26 @@
#include <iostream>
#include <cstdlib>
#include <time.h>
const int LOW = 1;
const int HIGH = 32000;
using namespace std;
int main()
{
int randomNumber;
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
for (int i = 0; i < 10; i++)
{
randomNumber = rand() % (HIGH - LOW + 1) + LOW;
cout << randomNumber << " ";
}
cout << "...";
return 0;
}
/*
312 7423 23444 16008 31816 1823 29315 17424 11753 18384 ...

View File

@ -0,0 +1,141 @@
/*This is a C++ Program to multiply two signed numbers using booths algorithm. Booths multiplication algorithm is a multiplication algorithm that multiplies two signed binary numbers in twos complement notation. Booth used desk calculators that were faster at shifting than adding and created the algorithm to increase their speed. Booths algorithm is of interest in the study of computer architecture.*/
#include<iostream>
#include<conio.h>
using namespace std;
void add(int a[], int x[], int qrn);
void complement(int a[], int n)
{
int i;
int x[8] = { NULL };
x[0] = 1;
for (i = 0; i < n; i++)
{
a[i] = (a[i] + 1) % 2;
}
add(a, x, n);
}
void add(int ac[], int x[], int qrn)
{
int i, c = 0;
for (i = 0; i < qrn; i++)
{
ac[i] = ac[i] + x[i] + c;
if (ac[i] > 1)
{
ac[i] = ac[i] % 2;
c = 1;
}
else
c = 0;
}
}
void ashr(int ac[], int qr[], int &qn, int qrn)
{
int temp, i;
temp = ac[0];
qn = qr[0];
cout << "\t\tashr\t\t";
for (i = 0; i < qrn - 1; i++)
{
ac[i] = ac[i + 1];
qr[i] = qr[i + 1];
}
qr[qrn - 1] = temp;
}
void display(int ac[], int qr[], int qrn)
{
int i;
for (i = qrn - 1; i >= 0; i--)
cout << ac[i];
cout << " ";
for (i = qrn - 1; i >= 0; i--)
cout << qr[i];
}
int main(int argc, char **argv)
{
int mt[10], br[10], qr[10], sc, ac[10] = { 0 };
int brn, qrn, i, qn, temp;
cout
<< "\n--Enter the multiplicand and multipier in signed 2's complement form if negative--";
cout << "\n Number of multiplicand bit=";
cin >> brn;
cout << "\nmultiplicand=";
for (i = brn - 1; i >= 0; i--)
cin >> br[i]; //multiplicand
for (i = brn - 1; i >= 0; i--)
mt[i] = br[i]; // copy multipier to temp array mt[]
complement(mt, brn);
cout << "\nNo. of multiplier bit=";
cin >> qrn;
sc = qrn; //sequence counter
cout << "Multiplier=";
for (i = qrn - 1; i >= 0; i--)
cin >> qr[i]; //multiplier
qn = 0;
temp = 0;
cout << "qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc\n";
cout << "\t\t\tinitial\t\t";
display(ac, qr, qrn);
cout << "\t\t" << sc << "\n";
while (sc != 0)
{
cout << qr[0] << "\t" << qn;
if ((qn + qr[0]) == 1)
{
if (temp == 0)
{
add(ac, mt, qrn);
cout << "\t\tsubtracting BR\t";
for (i = qrn - 1; i >= 0; i--)
cout << ac[i];
temp = 1;
}
else if (temp == 1)
{
add(ac, br, qrn);
cout << "\t\tadding BR\t";
for (i = qrn - 1; i >= 0; i--)
cout << ac[i];
temp = 0;
}
cout << "\n\t";
ashr(ac, qr, qn, qrn);
}
else if (qn - qr[0] == 0)
ashr(ac, qr, qn, qrn);
display(ac, qr, qrn);
cout << "\t";
sc--;
cout << "\t" << sc << "\n";
}
cout << "Result=";
display(ac, qr, qrn);
}
/*
--Enter the multiplicand and multipier in signed 2's complement form if negative--
Number of multiplicand bit=5
Multiplicand=1 0 1 1 1
Number of multiplier bit=5
Multiplier=1 0 0 1 1
qn q[n+1] BR AC QR sc
initial 00000 10011 5
1 0 subtracting BR 01001
ashr 00100 11001 4
1 1 ashr 00010 01100 3
0 1 adding BR 11001
ashr 11100 10110 2
0 0 ashr 11110 01011 1
1 0 subtracting BR 00111
ashr 00011 10101 0
Result=00011 10101

View File

@ -0,0 +1,129 @@
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
cout << "Enter the dimension of the matrices: ";
int n;
cin >> n;
cout << "Enter the 1st matrix: ";
double a[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
cout << "Enter the 2nd matrix: ";
double b[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> b[i][j];
}
}
cout << "Enter the result matrix: ";
double c[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> c[i][j];
}
}
//random generation of the r vector containing only 0/1 as its elements
double r[n][1];
for (int i = 0; i < n; i++)
{
r[i][0] = rand() % 2;
cout << r[i][0] << " ";
}
//test A * (b*r) - (C*) = 0
double br[n][1];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 1; j++)
{
for (int k = 0; k < n; k++)
{
br[i][j] = br[i][j] + b[i][k] * r[k][j];
}
}
}
double cr[n][1];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 1; j++)
{
for (int k = 0; k < n; k++)
{
cr[i][j] = cr[i][j] + c[i][k] * r[k][j];
}
}
}
double abr[n][1];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 1; j++)
{
for (int k = 0; k < n; k++)
{
abr[i][j] = abr[i][j] + a[i][k] * br[k][j];
}
}
}
// br = multiplyVector(b, r, n);
// cr = multiplyVector(c, r, n);
// abr = multiplyVector(a, br, n);
//abr-cr
for (int i = 0; i < n; i++)
{
abr[i][0] -= cr[i][0];
}
bool flag = true;
for (int i = 0; i < n; i++)
{
if (abr[i][0] == 0)
continue;
else
flag = false;
}
if (flag == true)
cout << "Yes";
else
cout << "No";
}
/*
Enter the dimension of the matrices: 2
Enter the 1st matrix:
1 2
2 3
Enter the 2nd matrix:
1 3
3 4
Enter the result matrix:
9 9
14 15
Yes
Enter the dimesion of the matrices:
2
Enter the 1st matrix:
2 3
3 4
Enter the 2st matrix:
1 0
1 2
Enter the result matrix:
6 5
8 7
Yes

View File

@ -0,0 +1,37 @@
/*
* C++ Program to Implement Euler Theorem
*/
#include <iostream>
#include <vector>
using namespace std;
vector<int> inverseArray(int n, int m)
{
vector<int> modInverse(n + 1, 0);
modInverse[1] = 1;
for (int i = 2; i <= n; i++)
{
modInverse[i] = (-(m / i) * modInverse[m % i]) % m + m;
}
return modInverse;
}
//Main
int main()
{
vector<int>::iterator it;
int a, m;
cout<<"Enter number to find modular multiplicative inverse: ";
cin>>a;
cout<<"Enter Modular Value: ";
cin>>m;
cout<<inverseArray(a, m)[a]<<endl;
}
/*
Enter number to find modular multiplicative inverse: 5
Enter Modular Value: 7
3
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,55 @@
/*
* C++ Program to Implement Extended Eucledian Algorithm
*/
#include <iostream>
#include <utility>
using namespace std;
/* return the gcd of a and b followed by the pair x and y of
equation ax + by = gcd(a,b)
*/
pair<int, pair<int, int> > extendedEuclid(int a, int b)
{
int x = 1, y = 0;
int xLast = 0, yLast = 1;
int q, r, m, n;
while (a != 0)
{
q = b / a;
r = b % a;
m = xLast - q * x;
n = yLast - q * y;
xLast = x;
yLast = y;
x = m;
y = n;
b = a;
a = r;
}
return make_pair(b, make_pair(xLast, yLast));
}
int modInverse(int a, int m)
{
return (extendedEuclid(a, m).second.first + m) % m;
}
//Main
int main()
{
int a, m;
cout<<"Enter number to find modular multiplicative inverse: ";
cin>>a;
cout<<"Enter Modular Value: ";
cin>>m;
cout<<modInverse(a, m)<<endl;
}
/*
Enter number to find modular multiplicative inverse: 133
Enter Modular Value: 135
67
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,67 @@
/*
* C++ Program to Implement Fermat Primality Test
*/
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
/*
* modular exponentiation
*/
ll modulo(ll base, ll exponent, ll mod)
{
ll x = 1;
ll y = base;
while (exponent > 0)
{
if (exponent % 2 == 1)
x = (x * y) % mod;
y = (y * y) % mod;
exponent = exponent / 2;
}
return x % mod;
}
/*
* Fermat's test for checking primality
*/
bool Fermat(ll p, int iterations)
{
if (p == 1)
{
return false;
}
for (int i = 0; i < iterations; i++)
{
ll a = rand() % (p - 1) + 1;
if (modulo(a, p - 1, p) != 1)
{
return false;
}
}
return true;
}
/*
* Main
*/
int main()
{
int iteration = 50;
ll num;
cout<<"Enter integer to test primality: ";
cin>>num;
if (Fermat(num, iteration))
cout<<num<<" is prime"<<endl;
else
cout<<num<<" is not prime"<<endl;
return 0;
}
/*
Enter integer to test primality: 479001599
479001599 is prime
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,49 @@
/*
* C++ Program to Implement Fermat's Little Theorem
*/
#include <iostream>
using namespace std;
/* calculates (a^b)%MOD */
int pow(int a, int b, int MOD)
{
int x = 1, y = a;
while (b > 0)
{
if (b % 2 == 1)
{
x = (x * y);
if (x > MOD)
x %= MOD;
}
y = (y * y);
if (y > MOD)
y %= MOD;
b /= 2;
}
return x;
}
int modInverse(int a, int m)
{
return pow(a, m - 2, m);
}
//Main
int main()
{
int a, m;
cout<<"Enter number to find modular multiplicative inverse: ";
cin>>a;
cout<<"Enter Modular Value: ";
cin>>m;
cout<<modInverse(a, m)<<endl;
}
/*
Enter number to find modular multiplicative inverse: 1111
Enter Modular Value: 331
216
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,48 @@
/*This is a C++ Program to shuffle array using Fisher-Yates algorithm. The FisherYates shuffle (named after Ronald Fisher and Frank Yates), also known as the Knuth shuffle (after Donald Knuth), is an algorithm for generating a random permutation of a finite set—in plain terms, for randomly shuffling the set. A variant of the FisherYates shuffle, known as Sattolos algorithm, may be used to generate random cycles of length n instead. The FisherYates shuffle is unbiased, so that every permutation is equally likely. The modern version of the algorithm is also rather efficient, requiring only time proportional to the number of items being shuffled and no additional storage space.*/
#include <iostream>
#include <stdlib.h>
using namespace std;
void fisherYatesShuffling(int *arr, int n)
{
int a[n];
int ind[n];
for (int i = 0; i < n; i++)
ind[i] = 0;
int index;
for (int i = 0; i < n; i++)
{
do
{
index = rand() % n;
}
while (ind[index] != 0);
ind[index] = 1;
a[i] = *(arr + index);
}
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
}
int main(int argc, char **argv)
{
cout << "Enter the array size: ";
int n;
cin >> n;
cout << "Enter the array elements: ";
int a[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
fisherYatesShuffling(a, n);
}
/*
Enter the array size: 7
Enter the array elements: 12 23 34 45 56 67 78
78 23 67 45 34 12 56

View File

@ -0,0 +1,80 @@
#include<iostream>
#include<conio.h>
using namespace std;
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];
}
printf("x%d = %f ", i + 1, y[i]);
}
cout << "\n";
m--;
}
return 0;
}
/*
Enter size of 2d array(Square matrix) : 3
Enter values no :(0, 0) 2
Enter values no :(0, 1) 3
Enter values no :(0, 2) 1
Enter values no :(1, 0) 5
Enter values no :(1, 1) 4
Enter values no :(1, 2) 6
Enter values no :(2, 0) 8
Enter values no :(2, 1) 7
Enter values no :(2, 2) 9
Enter Values to the right side of equation
Enter values no :(0, 3) 2
Enter values no :(1, 3) 3
Enter values no :(2, 3) 4
Enter initial values of x
Enter values no. :(0): 0
Enter values no. :(1): 0
Enter values no. :(2): 0
Enter the no. of iteration : 4
x1 = 1.000000 x2 = -0.500000 x3 = -0.055556
x1 = 1.777778 x2 = -1.388889 x3 = -0.055556
x1 = 3.111111 x2 = -3.055555 x3 = 0.055555
x1 = 5.555555 x2 = -6.277777 x3 = 0.388889

View File

@ -0,0 +1,98 @@
/*
* C++ Program to Implement Miller Rabin Primality Test
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
#define ll long long
using namespace std;
/*
* calculates (a * b) % c taking into account that a * b might overflow
*/
ll mulmod(ll a, ll b, ll mod)
{
ll x = 0,y = a % mod;
while (b > 0)
{
if (b % 2 == 1)
{
x = (x + y) % mod;
}
y = (y * 2) % mod;
b /= 2;
}
return x % mod;
}
/*
* modular exponentiation
*/
ll modulo(ll base, ll exponent, ll mod)
{
ll x = 1;
ll y = base;
while (exponent > 0)
{
if (exponent % 2 == 1)
x = (x * y) % mod;
y = (y * y) % mod;
exponent = exponent / 2;
}
return x % mod;
}
/*
* Miller-Rabin primality test, iteration signifies the accuracy
*/
bool Miller(ll p,int iteration)
{
if (p < 2)
{
return false;
}
if (p != 2 && p % 2==0)
{
return false;
}
ll s = p - 1;
while (s % 2 == 0)
{
s /= 2;
}
for (int i = 0; i < iteration; i++)
{
ll a = rand() % (p - 1) + 1, temp = s;
ll mod = modulo(a, temp, p);
while (temp != p - 1 && mod != 1 && mod != p - 1)
{
mod = mulmod(mod, mod, p);
temp *= 2;
}
if (mod != p - 1 && temp % 2 == 0)
{
return false;
}
}
return true;
}
//Main
int main()
{
int iteration = 5;
ll num;
cout<<"Enter integer to test primality: ";
cin>>num;
if (Miller(num, iteration))
cout<<num<<" is prime"<<endl;
else
cout<<num<<" is not prime"<<endl;
return 0;
}
/*
Enter integer to test primality: 127
127 is prime
------------------
(program exited with code: 1)
Press return to continue

View File

@ -0,0 +1,48 @@
/*
* C++ Program to Implement Modular Exponentiation Algorithm
*/
#include <iostream>
#define ll long long
using namespace std;
/*
* Function to calculate modulus of x raised to the power y
*/
ll modular_pow(ll base, ll exponent, int modulus)
{
ll result = 1;
while (exponent > 0)
{
if (exponent % 2 == 1)
result = (result * base) % modulus;
exponent = exponent >> 1;
base = (base * base) % modulus;
}
return result;
}
/*
* Main
*/
int main()
{
ll x, y;
int mod;
cout<<"Enter Base Value: ";
cin>>x;
cout<<"Enter Exponent: ";
cin>>y;
cout<<"Enter Modular Value: ";
cin>>mod;
cout<<modular_pow(x, y, mod);
return 0;
}
/*
Enter Base Value: 2
Enter Exponent: 5
Enter Modular Value: 23
9
------------------
(program exited with code: 1)
Press return to continue

Some files were not shown because too many files have changed in this diff Show More