filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/online_challenges/src/codechef/MNMX/MNMX.c | #include <stdio.h>
int main()
{
int t;
scanf("%d", & t);
while (t--)
{
long long int n, i;
scanf("%lld", & n);
long long int a[n];
for (i = 0; i < n; ++i)
{
scanf("%lld", & a[i]);
}
long long int min = a[0];
for (i = 0; i < n; ++i)
{
if (a[i] < min)
{
min = a[i];
}
}
printf("%lld\n", min * (n - 1));
}
return 0;
}
|
code/online_challenges/src/codechef/MNMX/README.md | # Problem Link:
[MNMX](https://www.codechef.com/problems/MNMX/)
# Description
Chef loves to play with arrays by himself. Today, he has an array A consisting of N distinct integers. He wants to perform the following operation on his array A.
Select a pair of adjacent integers and remove the larger one of these two. This decreases the array size by 1. Cost of this operation will be equal to the smaller of them.
Find out minimum sum of costs of operations needed to convert the array into a single element.
# Input
First line of input contains a single integer T denoting the number of test cases. First line of each test case starts with an integer N denoting the size of the array A. Next line of input contains N space separated integers, where the ith integer denotes the value Ai.
# Output
For each test case, print the minimum cost required for the transformation.
# Constraints
1 ≤ T ≤ 10
2 ≤ N ≤ 50000
1 ≤ Ai ≤ 105
# Subtasks
Subtask 1 : 2 ≤ N ≤ 15 : 35 pts
Subtask 2 : 2 ≤ N ≤ 100 : 25 pts
Subtask 3 : 2 ≤ N ≤ 50000 : 40 pts
# Example
Input
2
2
3 4
3
4 2 5
Output
3
4
# Explanation
Test 1 : Chef will make only 1 move: pick up both the elements (that is, 3 and 4), remove the larger one (4), incurring a cost equal to the smaller one (3). |
code/online_challenges/src/codechef/NBONACCI/NBONACCI.cpp | #include <iostream>
#include <algorithm>
int main ()
{
int n,q;
std::cin >> n >> q;
int a[n];
for (int i = 0; i < n; ++i)
{
std::cin>>a[i];
}
int x = 0;
int xors[n] = {0};
for (int i = 0; i < n; ++i)
{
x = x ^ a[i];
xors[i] = x;
}
while (q--)
{
int k;
std::cin >> k;
int idx = k % (n + 1);
if (idx > 0)
std::cout << xors[idx - 1] << "\n";
else std::cout << "0\n";
}
return 0;
}
|
code/online_challenges/src/codechef/NBONACCI/README.md | # Problem link
[NBONACCI](https://www.codechef.com/problems/NBONACCI).
# Description
An N-bonacci sequence is an infinite sequence F1,F2,… such that for each integer i>N, Fi is calculated as f(Fi−1,Fi−2,…,Fi−N), where f is some function. A XOR N-bonacci sequence is an N-bonacci sequence for which f(Fi−1,Fi−2,…,Fi−N)=Fi−1⊕Fi−2⊕…⊕Fi−N, where ⊕
denotes the bitwise XOR operation.
Recently, Chef has found an interesting sequence S1,S2,…, which is obtained from prefix XORs of a XOR N-bonacci sequence F1,F2,…. Formally, for each positive integer i, Si=F1⊕F2⊕…⊕Fi. You are given the first N elements of the sequence F, which uniquely determine the entire sequence S.
You should answer Q queries. In each query, you are given an index k and you should calculate Sk. It is guaranteed that in each query, Sk does not exceed 10^50.
|
code/online_challenges/src/codechef/NEWSCH/NEWSCH.cpp | #include <iostream>
#include <cstring>
using namespace std;
#define MOD 1000000007
uint64_t modmul(const uint64_t x, const uint64_t y)
{
if (x > (1 << 30) && y > (1 << 30))
return ((x >> 30)*((y << 30) % MOD) + y*(x & ((1 << 30) - 1))) % MOD;
uint64_t z = x*y;
if (z >= MOD)
z %= MOD;
return z;
}
uint64_t modpow(uint64_t base, int exp)
{
uint64_t result = 1;
for (;;)
{
if (exp & 1)
result = modmul(result, base);
exp >>= 1;
if (!exp)
break;
base = modmul(base, base);
}
return result;
}
int main()
{
int t;
cin >> t;
while (t-- > 0)
{
int n;
cin >> n;
uint64_t ans = modpow(3, n);
if (n % 2 == 0)
ans = (ans + 3) % MOD;
else
ans = (ans + MOD - 3) % MOD;
cout << ans << endl;
}
return 0;
}
|
code/online_challenges/src/codechef/NEWSCH/README.md | # Problem Link
[NEWSCH](https://www.codechef.com/problems/NEWSCH)
# Description
Scheme? - Too loudly said. Just a new idea. Now Chef is expanding his business. He wants to make some new restaurants in the big city of Lviv. To make his business competitive he should interest customers. Now he knows how. But don't tell anyone - it is a secret plan. Chef knows four national Ukrainian dishes - salo, borsch, varenyky and galushky. It is too few, of course, but enough for the beginning. Every day in his restaurant will be a dish of the day among these four ones. And dishes of the consecutive days must be different. To make the scheme more refined the dish of the first day and the dish of the last day must be different too. Now he wants his assistant to make schedule for some period. Chef suspects that there is more than one possible schedule. Hence he wants his assistant to prepare all possible plans so that he can choose the best one among them. He asks you for help. At first tell him how many such schedules exist. Since the answer can be large output it modulo 109 + 7, that is, you need to output the remainder of division of the actual answer by 109 + 7. |
code/online_challenges/src/codechef/NUKES/NUKES.c | #include <stdio.h>
int main(void)
{
int n, max, k;
scanf("%d %d %d", & n, & max, & k);
int i = 0;
int l = max + 1;
while (i < k)
{
printf("%d ", n % l);
n = n / l;
++i;
}
printf("\n");
return 0;
}
|
code/online_challenges/src/codechef/NUKES/README.md | # Problem Link:
[NUKES](https://www.codechef.com/problems/NUKES/)
# Description
There are K nuclear reactor chambers labelled from 0 to K-1. Particles are bombarded onto chamber 0. The particles keep collecting in the chamber 0. However if at any time, there are more than N particles in a chamber, a reaction will cause 1 particle to move to the immediate next chamber(if current chamber is 0, then to chamber number 1), and all the particles in the current chamber will be be destroyed and same continues till no chamber has number of particles greater than N. Given K,N and the total number of particles bombarded (A), find the final distribution of particles in the K chambers. Particles are bombarded one at a time. After one particle is bombarded, the set of reactions, as described, take place. After all reactions are over, the next particle is bombarded. If a particle is going out from the last chamber, it has nowhere to go and is lost. |
code/online_challenges/src/codechef/NUMGAME2/NUMGAME2.c | #include <stdio.h>
int main(void)
{
int t;
scanf("%d", & t);
while (t--)
{
long long int n;
scanf("%lld", & n);
if (n % 4 == 1)
printf("ALICE\n");
else
printf("BOB\n");
}
return 0;
}
|
code/online_challenges/src/codechef/NUMGAME2/README.md | # Problem Link:
[NUMGAME2](https://www.codechef.com/problems/NUMGAME2)
# Description
Alice and Bob play the following game.They choose a number N to play with.The runs are as follows :
1.Bob plays first and the two players alternate.
2.In his/her turn ,a player can subtract from N any prime number(including 1) less than N.The number thus obtained is the new N.
3.The person who cannot make a move in his/her turn loses the game.
Assuming both play optimally,who wins the game ?
|
code/online_challenges/src/codechef/OJUMPS/OJUMPS.c | #include<stdio.h>
int main()
{
long long int a;
scanf("%lld", & a);
long long int b = a % 6;
if (b == 0)
printf("yes\n");
else if (b == 1)
printf("yes\n");
else if (b == 3)
printf("yes\n");
else
printf("no\n");
return 0;
}
|
code/online_challenges/src/codechef/OJUMPS/README.md | # Problem Link:
[OJUMPS](https://www.codechef.com/problems/OJUMPS/)
# Description
This morning Chef wants to jump a little. In a few minutes he will arrive at the point 0. Then he will perform a lot of jumps in such a sequence: 1-jump, 2-jump, 3-jump, 1-jump, 2-jump, 3-jump, 1-jump, and so on.
1-jump means that if Chef is at the point x, he will jump to the point x+1.
2-jump means that if Chef is at the point x, he will jump to the point x+2.
3-jump means that if Chef is at the point x, he will jump to the point x+3.
Before the start Chef asks you: will he arrive at the point a after some number of jumps? |
code/online_challenges/src/codechef/P-BATTLE/PBATTLE.cpp | // Question link : https://www.codechef.com/submit/PBATTLE
//Author - Vishwas Kapoor
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
void solve(){
int n;
cin>>n;
vector<pair<int,int>> pg; // pokemon ground
fl(n){
int x;
cin>>x;
pg.push_back({x,i});
}
vector<int>pw; // pokemon water
fl(n){
int x;
cin>>x;
pw.push_back(x);
}
sort(pg.begin(), pg.end() );
priority_queue<int>pq;
pq.push(pw[pg[n-1].second]);
int count = 1;
for(int i = n-2; i >= 0; i--){
pq.push(pw[pg[i].second]);
if(pq.top() == pw[pg[i].second])
count++;
}
cout<<count<<endl;
}
signed main(){
IOS
int t;
cin>>t;
while(t--)
goddamn();
return 0;
}
|
code/online_challenges/src/codechef/PRIME1/PRIME1.c | #include <stdio.h>
#include <math.h>
int main()
{
int t;
scanf("%d", & t);
while (t--)
{
int m, n;
scanf("%d %d", & m, & n);
int i;
for (i = m; i <= n; ++i)
if (isPrime(i))
printf("%d\n", i);
printf("\n");
}
}
int isPrime(int n)
{
if (n == 1)
return 0;
else if (n == 2)
return 1;
int i;
for (i = 2; i < sqrt(n) + 1; ++i)
if (n % i == 0)
return 0;
return 1;
}
|
code/online_challenges/src/codechef/PRIME1/README.md | # Problem Link:
[PRIME1](https://www.codechef.com/problems/PRIME1/)
# Description
Ram wants to generate some prime numbers for his cryptosystem. Help him please! Your task is to generate all prime numbers between two given numbers. |
code/online_challenges/src/codechef/README.md | # Codechef
From [Codechef](https://www.codechef.com/):
CodeChef was created as a platform to help programmers make it big in the world of algorithms, computer programming and programming contests. At CodeChef we work hard to revive the geek in you by hosting a programming contest at the start of the month and another smaller programming challenge in the middle of the month. We also aim to have training sessions and discussions related to algorithms, binary search, technicalities like array size and the likes. Apart from providing a platform for programming competitions, CodeChef also has various algorithm tutorials and forum discussions to help those who are new to the world of computer programming.
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
|
code/online_challenges/src/codechef/RESQ/README.md | # Problem Link:
[RESQ](https://www.codechef.com/problems/RESQ/)
# Description
Our Chef is catering for a big corporate office party and is busy preparing different mouth watering dishes. The host has insisted that he serves his delicious cupcakes for dessert.
On the day of the party, the Chef was over-seeing all the food arrangements as well, ensuring that every item was in its designated position. The host was satisfied with everything except the cupcakes. He noticed they were arranged neatly in the shape of a rectangle. He asks the Chef to make it as square-like as possible.
The Chef is in no mood to waste his cupcakes by transforming it into a perfect square arrangement. Instead, to fool the host, he asks you to arrange the N cupcakes as a rectangle so that the difference between the length and the width is minimized. |
code/online_challenges/src/codechef/RESQ/RESQ.c | #include <stdio.h>
#include <math.h>
int fun(int area)
{
int p, j;
int flag = area - 1;
for (j = 1; j <= (int)(sqrt(area)); ++j)
if (area % j == 0)
{
p = abs(((int) area / j) - j);
if (p < flag)
flag = p;
}
return flag;
}
int main()
{
int n, i, area, ans;
scanf("%d", & n);
for (i = 0; i < n; ++i)
{
scanf("%d", & area);
ans = fun(area);
printf("%d\n", ans);
}
}
|
code/online_challenges/src/codechef/RIGHTRI/README.md | # Problem Link:
[RIGHTRI](https://www.codechef.com/problems/RIGHTRI/)
# Description
The Chef is given a list of N triangles. Each triangle is identfied by the coordinates of its three corners in the 2-D cartesian plane. His job is to figure out how many of the given triangles are right triangles. A right triangle is a triangle in which one angle is a 90 degree angle. The vertices of the triangles have integer coordinates and all the triangles given are valid( three points aren't colinear ). |
code/online_challenges/src/codechef/RIGHTRI/RIGHTRI.c | #include <stdio.h>
int main(void)
{
int t;
scanf("%d", & t);
int i, k = 0;
for (i = 0; i < t; i++)
{
int x1, x2, x3, y1, y2, y3;
scanf("%d%d%d%d%d%d", & x1, & y1, & x2, & y2, & x3, & y3);
float a = pow(x1 - x2, 2) + pow(y1 - y2, 2);
float b = pow(x2 - x3, 2) + pow(y2 - y3, 2);
float c = pow(x3 - x1, 2) + pow(y3 - y1, 2);
if (a + b == c || b + c == a || c + a == b)
k++;
}
printf("%d", k);
return 0;
}
|
code/online_challenges/src/codechef/RRCOPY/README.md | # Problem Link:
[RRCOPY](https://www.codechef.com/problems/RRCOPY/)
# Description
You had an array of integer numbers. You also had a beautiful operations called "Copy-Paste" which allowed you to copy any contiguous subsequence of your array and paste it in any position of your array. For example, if you have array [1, 2, 3, 4, 5] and copy it's subsequence from the second to the fourth element and paste it after the third one, then you will get [1, 2, 3, 2, 3, 4, 4, 5] array. You remember that you have done a finite(probably zero) number of such operations over your initial array and got an array A as a result. Unfortunately you don't remember the initial array itself, so you would like to know what could it be. You are interested by the smallest such array. So the task is to find the minimal size(length) of the array that A can be obtained from by using "Copy-Paste" operations.
|
code/online_challenges/src/codechef/RRCOPY/RRCOPY.c | #include <stdio.h>
#include <string.h>
int main(void)
{
int t;
scanf("%d", & t);
while (t--)
{
int n, h[1000000] = {0};
scanf("%d", & n);
int count = 0;
while (n--)
{
int temp;
scanf("%d", & temp);
if (h[temp] == 0)
{
count++;
h[temp]++;
}
}
printf("%d\n", count);
}
return 0;
}
|
code/online_challenges/src/codechef/SALARY/README.md | # Problem Link:
[SALARY](https://www.codechef.com/problems/SALARY/)
# Description
Little chief has his own restaurant in the city. There are N workers there. Each worker has his own salary. The salary of the i-th worker equals to Wi (i = 1, 2, ..., N). Once, chief decided to equalize all workers, that is, he wants to make salaries of all workers to be equal. But for this goal he can use only one operation: choose some worker and increase by 1 salary of each worker, except the salary of the chosen worker. In other words, the chosen worker is the loser, who will be the only worker, whose salary will be not increased during this particular operation. But loser-worker can be different for different operations, of course. Chief can use this operation as many times as he wants. But he is a busy man. That's why he wants to minimize the total number of operations needed to equalize all workers. Your task is to find this number. |
code/online_challenges/src/codechef/SALARY/SALARY.c | #include<stdio.h>
int main()
{
int t;
scanf("%d", & t);
int T[t];
int i, j;
for (i = 0; i < t; ++i)
{
int n;
scanf("%d", & n);
int A[n];
int min = 32767;
for (j = 0; j < n; ++j)
{
scanf("%d", & A[j]);
if (A[j] < min)
{
min = A[j];
}
}
int count = 0;
for (j = 0; j < n; ++j)
{
count += (A[j] - min);
}
T[i] = count
}
for (i = 0; i < t; ++i)
{
printf("%d\n", T[i]);
}
return 0;
}
|
code/online_challenges/src/codechef/SLAB/README.md | # Problem Link
[SLAB](https://www.codechef.com/COOK115B/problems/SLAB)
# Description
In India, every individual is charged with income tax on the total income each year. This tax is applied to specific ranges of income, which are called income tax slabs. The slabs of income tax keep changing from year to year. This fiscal year (2020-21), the tax slabs and their respective tax rates are as follows:
| Total income (in rupees) | Tax rate |
| ----------------------------------- | -------- |
| up to Rs. 250,000 | 0% |
| from Rs. 250,001 to Rs. 500,000 | 5% |
| from Rs. 500,001 to Rs. 750,000 | 10% |
| from Rs. 750,001 to Rs. 1,000,000 | 15% |
| from Rs. 1,000,001 to Rs. 1,250,000 | 20% |
| from Rs. 1,250,001 to Rs. 1,500,000 | 25% |
| above Rs. 1,500,000 | 30% |
See the sample explanation for details on how the income tax is calculated.
You are given Chef's *total income*: N rupees (Rs.). Find his *net income*. The net income is calculated by subtracting the total tax (also called *tax reduction*) from the total income. Note that you do not need to worry about any other kind of tax reductions, only the one described above.
|
code/online_challenges/src/codechef/SLAB/SLAB.cpp | // Part of Cosmos by OpenGenus
#include <iostream>
using namespace std;
int main ()
{
int t;
cin >> t;
while (t --)
{
long long int total, net, tax;
cin >> total;
if (total <= 250000)
{
net = total;
}
else if ((250000 < total) && (total <= 500000))
{
tax = 0.05 * (total - 250000);
net = total - tax;
}
else if ((500000 < total) && (total <= 750000))
{
tax = 0.05 * ( 500000- 250000) + 0.10 * (total - 500000);
net = total - tax;
}
else if ((750000 < total) && (total <= 1000000))
{
tax = 0.05 * (500000 - 250000) + 0.10 * (750000 - 500000) + 0.15 * (total - 750000);
net = total - tax;
}
else if ((1000000 < total) && (total <= 1250000))
{
tax = 0.05 * (500000 - 250000) + 0.10 * (750000 - 500000) + 0.15 * (1000000 - 750000) + 0.20 * (total - 1000000);
net = total - tax;
}
else if ((1250000 < total) && (total <= 1500000))
{
tax = 0.05 *(500000 - 250000) + 0.10 * (750000 - 500000) + 0.15 * (1000000 - 750000) + 0.20 * (1250000 - 1000000) + 0.25 * (total - 1250000);
net = total - tax;
}
else if (total > 1500000)
{
tax = 0.05 * (500000 - 250000) + 0.10 * (750000 - 500000) + 0.15 * (1000000 - 750000) + 0.20 * (1250000 - 1000000) + 0.25 * (1500000 - 1250000) + 0.30 * (total - 1500000);
net = total - tax;
}
cout << net << endl;
}
return 0;
}
|
code/online_challenges/src/codechef/SLAB/Slab.java | import java.io.*;
import java.util.*;
class Slab {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
int a = 12500;
int b = 25000;
int c = 37500;
int d = 50000;
int e = 62500;
while (t-- > 0) {
long n = s.nextLong();
long ans = 0;
if (n <= 250000) {
System.out.println(n);
} else {
if (n >= 250001 && n <= 500000) {
long div = (long) ((n - 250000) * 0.05);
System.out.println(n - div);
} else if (n >= 500001 && n <= 750000) {
long div = (long) ((n - 500000) * 0.1);
System.out.println(n - a - div);
} else if (n >= 750001 && n <= 1000000) {
long div = (long) ((n - 750000) * 0.15);
System.out.println(n - a - b - div);
} else if (n >= 1000001 && n <= 1250000) {
long div = (long) ((n - 1000000) * 0.2);
System.out.println(n - a - b - c - div);
} else if (n >= 1250001 && n <= 1500000) {
long div = (long) ((n - 1250000) * 0.25);
System.out.println(n - a - b - c - d - div);
} else if (n > 1500000) {
long f = (long) ((n - 1500000) * 0.3);
System.out.println(n - a - b - c - d - e - f);
}
}
}
}
}
/*
TEST CASE
INPUT
2
600000
250000
OUTPUT
577500
250000
*/
|
code/online_challenges/src/codechef/SNUG_FIT/README.md | # Problem Link:
[SNUG_FIT](https://www.codechef.com/FEB20B/problems/SNUG_FIT)
# Description
Geometry expert Nitin is thinking about a problem with parabolas, icosahedrons, crescents and trapezoids, but for now, to encourage beginners, he chooses to work with circles and rectangles.
You are given two sequences A1,A2,…,AN and B1,B2,…,BN. You should choose a permutation P1,P2,…,PN of the integers 1 through N and construct N rectangles with dimensions A1×BP1,A2×BP2,…,AN×BPN. Then, for each of these rectangles, you should construct an inscribed circle, i.e. a circle with the maximum possible area that is completely contained in that rectangle.
Let S be the sum of diameters of these N circles. Your task is to find the maximum value of S.
|
code/online_challenges/src/codechef/SNUG_FIT/snug_fit.cpp | #include <algorithm>
#include <iostream>
#include <vector>
int main() {
int t;
std::cin >> t;
while (t--) {
int n, i, sum = 0;
std::cin >> n;
std::vector<int> a(n), b(n);
for (i = 0; i < n; ++i) {
std::cin >> a[i];
}
for (i = 0; i < n; ++i) {
std::cin >> b[i];
}
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
for (i = 0; i < n; ++i) {
sum += std::min(a[i], b[i]);
}
std::cout << sum << "\n";
}
}
|
code/online_challenges/src/codechef/SPCANDY/README.md | # Problem Link:
[SPCANDY](https://www.codechef.com/problems/SPCANDY/)
# Description
Cyael is a teacher at a very famous school in Byteland and she is known by her students for being very polite to them and also to encourage them to get good marks on their tests.
Then, if they get good marks she will reward them with candies :) However, she knows they are all very good at Mathematics, so she decided to split the candies evenly to all the students she considers worth of receiving them, so they don't fight with each other.
She has a bag which initially contains N candies and she intends to split the candies evenly to K students. To do this she will proceed as follows: while she has more than K candies she will give exactly 1 candy to each student until she has less than K candies. On this situation, as she can't split candies equally among all students she will keep the remaining candies to herself.
Your job is to tell how many candies will each student and the teacher receive after the splitting is performed. |
code/online_challenges/src/codechef/SPCANDY/SPCANDY.c | #include <stdio.h>
int main(void)
{
long long int t;
scanf("%lld", & t);
while (t--)
{
long long int n, k;
scanf("%lld %lld", & n, & k);
if (k != 0)
printf("%lld %lld\n", n / k, n % k);
else
printf("0 %lld\n", n);
}
return 0;
}
|
code/online_challenges/src/codechef/STFOOD/README.md | # Problem Link:
[CASH](https://www.codechef.com/FEB20B/problems/CASH/)
# Description
in Chefland, there is a very famous street where N types of street food (numbered 1 through N) are offered. For each valid i, there are Si stores that offer food of the i-th type, the price of one piece of food of this type is Vi (the same in each of these stores) and each day, Pi people come to buy it; each of these people wants to buy one piece of food of the i-th type.
Chef is planning to open a new store at this street, where he would offer food of one of these N types. Chef assumes that the people who want to buy the type of food he'd offer will split equally among all stores that offer it, and if this is impossible, i.e. the number of these people p is not divisible by the number of these stores s, then only ⌊p/s⌋ people will buy food from Chef.
Chef wants to maximize his daily profit. Help Chef choose which type of food to offer and find the maximum daily profit he can make. of RR. |
code/online_challenges/src/codechef/STFOOD/Stfood.java | import java.io.*;
import java.util.*;
class Stfood {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t-- > 0) {
int n = s.nextInt();
int maxprofit = 0;
for (int i = 0; i < n; i++) {
int stores = s.nextInt();
int p = s.nextInt();
int v = s.nextInt();
int profit = (p / (stores + 1)) * v;
// updating maxprofit
if (maxprofit < profit) {
maxprofit = profit;
}
}
System.out.println(maxprofit);
}
}
}
/*
TEST CASES
INPUT
2
3
4 6 8
2 6 6
1 4 3
1
7 7 4
OUTPUT
12
0
*/
|
code/online_challenges/src/codechef/STONES/README.md | # Problem Link:
[STONES](https://www.codechef.com/problems/STONES/)
# Description
Soma is a fashionable girl. She absolutely loves shiny stones that she can put on as jewellery accessories. She has been collecting stones since her childhood - now she has become really good with identifying which ones are fake and which ones are not. Her King requested for her help in mining precious stones, so she has told him which all stones are jewels and which are not. Given her description, your task is to count the number of jewel stones.
More formally, you're given a string J composed of latin characters where each character is a jewel. You're also given a string S composed of latin characters where each character is a mined stone. You have to find out how many characters of S are in J as well. |
code/online_challenges/src/codechef/STONES/STONES.c | #include <stdio.h>
#include <string.h>
int main(void)
{
int t;
scanf("%d", & t);
while (t--)
{
char s[100], r[100];
int count = 0;
scanf("%s", s);
scanf("%s", r);
int l = strlen(r);
int i;
for (i = 0; < l; ++i)
{
int j;
for (j = 0; j < l; ++j)
{
if (s[j] == r[i])
{
++count;
break;
}
}
}
printf("%d\n", count);
}
return 0;
}
|
code/online_challenges/src/codechef/STRWN/README.md | # Problem Link
[STRWN](https://www.codechef.com/COMR2019/problems/STRWN)
# Description
This is a fight between weapons. There are 3 type of weapons - Dragonglass, Valyrian Steel and Wild Fire. Now, the result of a fight between any 2 weapons is known to be as below:
Dragonglass defeats Valyrian Steel
Valyrian Steel defeats Wild Fire
Wild Fire defeats Dragonglass
Here, note that match between 2 weapons of same type results in draw.
Now, there are D number of dragonglasses, V number of swords of Valyrian Steel and W number of containers of Wild Fire. At a time you can choose any 2 weapons (possibly same weapons) from remaining and make them fight.
If weapon x and weapon y fight, and suppose x defeats y , then y is out of the game and x returns to the respective group of the remaining weapons.
If weapon x and weapon y fight, and suppose the match is draw, then both of them return to their respective groups.
Your task is to minimize the total number of remaining weapons of all 3 types if the game can go on forever.
**Note:** After a weapon wins and return to the group of weapons, you can again choose any 2 weapons, that you want, from all the remaining ones. |
code/online_challenges/src/codechef/STRWN/STRWN.cpp | #include <iostream>
#define ll long long
#define ld long double
#define pb push_back
#define pp pop_back
#define mp make_pair
#define ff first
#define ss second
#define maxn 1000000007
#define PI 3.14159265358979323846
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//cout<<fixed<<setprecision(20);
ll a,b,c;
cin>>a>>b>>c;
if(a==0 && b==0 && c==0)
{
cout<<0<<endl;
return 0;
}
if(a==0 && b==0 && c>0)
{
cout<<c<<endl;
return 0;
}
if(a==0 && c==0 && b>0)
{
cout<<b<<endl;
return 0;
}
if(c==0 && b==0 && a>0)
{
cout<<a<<endl;
return 0;
}
if(a==0 && b>0 && c>0)
{
cout<<b<<endl;
return 0;
}
if(b==0 && a>0 && c>0)
{
cout<<c<<endl;
return 0;
}
if(c==0 && a>0 && b>0)
{
cout<<a<<endl;
return 0;
}
cout<<1<<endl;
return 0;
}
|
code/online_challenges/src/codechef/STUPMACH/Stupmach.java | import java.util.Scanner;
public class Stupmach {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t-- >0){
int n = s.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++){
arr[i] = s.nextInt();
}
long maxtokens = 0;
int min = arr[0];
for (int i = 0;i < n; i++){
if (min <= arr[i]) {
maxtokens += min;
}
else {
min = arr[i];
maxtokens += min;
}
}
System.out.println(maxtokens);
}
}
}
/*
TEST CASE
INPUT
1
3
2 1 3
OUTPUT
4
*/
|
code/online_challenges/src/codechef/TACHSTCK/README.md | # Problem Link:
[TACHSTCK](https://www.codechef.com/problems/TACHSTCK/)
# Description
[Chopsticks (singular: chopstick) are short, frequently tapered sticks used in pairs of equal length, which are used as the traditional eating utensils of China, Japan, Korea and Vietnam. Originated in ancient China, they can also be found in some areas of Tibet and Nepal that are close to Han Chinese populations, as well as areas of Thailand, Laos and Burma which have significant Chinese populations. Chopsticks are most commonly made of wood, bamboo or plastic, but in China, most are made out of bamboo. Chopsticks are held in the dominant hand, between the thumb and fingers, and used to pick up pieces of food.]
Retrieved from wikipedia
Actually, the two sticks in a pair of chopsticks need not be of the same length. A pair of sticks can be used to eat as long as the difference in their length is at most D. The Chef has N sticks in which the ith stick is L[i] units long. A stick can't be part of more than one pair of chopsticks. Help the Chef in pairing up the sticks to form the maximum number of usable pairs of chopsticks. |
code/online_challenges/src/codechef/TACHSTCK/TACHSTCK.c | #include <stdio.h>
#include <stdlib.h>
void merge(long long int arr[], long long int l, long long int m, long long int r)
{
long long int i, j, k;
long long int n1 = m - l + 1;
long long int n2 = r - m;
long long int L[n1], R[n2];
for (i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
} else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(long long int arr[], long long int l, long long int r)
{
if (l < r)
{
long long int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main()
{
long long int n, k, i, * a, count = 0;
scanf("%lld%lld", & n, & k);
a = (long long int * ) malloc(n * sizeof(long long int));
for (i = 0; i < n; ++i)
scanf("%lld", & a[i]);
mergeSort(a, 0, n - 1);
for (i = n - 1; i >= 0; --i)
{
if (i == 0)
continue;
else if ((a[i] - a[i - 1]) > k)
continue;
else
{
count += 1;
i -= 1;
}
}
printf("%lld\n", count);
return 0;
}
|
code/online_challenges/src/codechef/TOTR/README.md | # Problem Link:
[TOTR](https://www.codechef.com/problems/TOTR)
# Description
A tourist is visiting Byteland. The tourist knows English very well. The language of Byteland is rather different from English. To be exact it differs in following points:
Bytelandian alphabet has the same letters as English one, but possibly different in meaning. Like 'A' in Bytelandian may be 'M' in English. However this does not mean that 'M' in Bytelandian must be 'A' in English. More formally, Bytelindian alphabet is a permutation of English alphabet. It will be given to you and could be any possible permutation. Don't assume any other condition.
People of Byteland don't like to use invisible character for separating words. Hence instead of space (' ') they use underscore ('_'). Other punctuation symbols, like '?', '!' remain the same as in English.
The tourist is carrying "The dummies guide to Bytelandian", for translation. The book is serving his purpose nicely. But he is addicted to sharing on BaceFook, and shares his numerous conversations in Byteland on it. The conversations are rather long, and it is quite tedious to translate for his English friends, so he asks you to help him by writing a program to do the same. |
code/online_challenges/src/codechef/TOTR/TOTR.c | #include <stdio.h>
#include <string.h>
int main(void)
{
int t;
scanf("%d", & t);
while (t--)
{
int n, h[1000000] = {0};
scanf("%d", & n);
int count = 0;
while (n--)
{
int temp;
scanf("%d", & temp);
if (h[temp] == 0)
{
count++;
h[temp]++;
}
}
printf("%d\n", count);
}
return 0;
}
|
code/online_challenges/src/codechef/VOTERS/README.md | # Problem Link:
[VOTERS](https://www.codechef.com/problems/VOTERS/)
# Description
As you might remember, the collector of Siruseri had ordered a complete revision of the Voters List. He knew that constructing the list of voters is a difficult task, prone to errors. Some voters may have been away on vacation, others may have moved during the enrollment and so on.
To be as accurate as possible, he entrusted the task to three different officials. Each of them was to independently record the list of voters and send it to the collector. In Siruseri, every one has a ID number and the list would only list the ID numbers of the voters and not their names. The officials were expected to arrange the ID numbers in ascending order in their lists.
On receiving the lists, the Collector realised that there were discrepancies - the three lists were not identical. He decided to go with the majority. That is, he decided to construct the final list including only those ID numbers that appeared in at least 2 out of the 3 lists. For example if the three lists were
23 30 42 57 90
21 23 35 57 90 92
21 23 30 57 90
then the final list compiled by the collector would be:
21 23 30 57 90
The ID numbers 35, 42 and 92 which appeared in only one list each do not figure in the final list.
Your task is to help the collector by writing a program that produces the final list from the three given lists. |
code/online_challenges/src/codechef/VOTERS/VOTERS.c | #include<stdio.h>
int main()
{
int n1, n2, n3;
scanf("%ld %ld %ld", & n1, & n2, & n3);
int n[1000000] = {0};
int i;
for (i = 0; i < n1; ++i)
{
int x;
scanf("%ld", & x);
++n[x];
}
for (i = 0; i < n2; ++i)
{
int x;
scanf("%ld", & x);
++n[x];
}
for (i = 0; i < n3; ++i)
{
int x;
scanf("%ld", & x);
++n[x];
}
int count = 0;
for (i = 0; i < 1000000; ++i)
{
if (n[i] > 1)
++count;
}
printf("%ld\n", count);
for (i = 0; i < 1000000; ++i)
{
if (n[i] > 1)
printf("%ld\n", i);
}
return 0;
}
|
code/online_challenges/src/hackerrank/2d_array_ds/2d_array_ds.java | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the hourglassSum function below.
static int hourglassSum(int[][] arr) {
int[] sum = new int[16];
Arrays.fill(sum, 0);
int k = 0;
for (int i = 0; i < arr.length - 2; i++) {
for (int j = 0; j < arr[0].length - 2; j++) {
sum[k] += arr[i][j] + arr[i][j + 1] + arr[i][j + 2];
sum[k] += arr[i + 1][j + 1];
sum[k] += arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
k++;
}
}
int max = sum[0];
for (int val: sum)
if (max < val)
max = val;
return max;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int[][] arr = new int[6][6];
for (int i = 0; i < 6; i++) {
String[] arrRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 6; j++) {
int arrItem = Integer.parseInt(arrRowItems[j]);
arr[i][j] = arrItem;
}
}
int result = hourglassSum(arr);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
|
code/online_challenges/src/hackerrank/3D_aurface_area/3D_surface_area.cpp | #include <iostream>
int main()
{
int h, w;
int a[110][110];
std::cin >> h >> w;
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j)
std::cin >> a[i][j];
}
int sum = 0;
for (int i = 0; i < h; ++i) {
if (i == 0) {
for (int j = 0; j < w; ++j) {
int temp = 0;
if (j == 0) {
temp = (a[i][j] - 1) * 4 + 6;
sum += temp;
}
else {
temp = (a[i][j] - 1) * 4 + 6;
int d = std::min(a[i][j - 1], a[i][j]);
temp -= (d * 2);
sum += temp;
}
}
}
else {
for (int j = 0; j < w; ++j) {
int temp = 0;
if (j == 0) {
temp = (a[i][j] - 1) * 4 + 6;
int d = std::min(a[i][j], a[i - 1][j]);
temp -= (d * 2);
sum += temp;
}
else {
temp = (a[i][j] - 1) * 4 + 6;
int d = std::min(a[i][j - 1], a[i][j]);
temp -= (d * 2);
d = std::min(a[i][j], a[i - 1][j]);
temp -= (d * 2);
sum += temp;
}
}
}
}
std::cout << sum << "\n";
return 0;
}
|
code/online_challenges/src/hackerrank/3D_aurface_area/README.md | ### Problem Link
[3D_aurface_area](https://www.hackerrank.com/challenges/3d-surface-area/problem?h_r=internal-search)
### Description
2D board A of size H * W with H rows and W columns. The board is divided into cells of size 1 * 1 with each cell indicated by it's coordinate (i,j). The cell (i,j) has an integer A<sub>i,j</sub> written on it. To create the toy Mason stacks A<sub>i,j</sub> number of cubes of size 1 * 1 * 1 on the cell (i,j) .
|
code/online_challenges/src/hackerrank/Counting_Valleys/Counting_Valleys.cpp | // Part of Cosmos by OpenGenus
#include <bits/stdc++.h>
using namespace std;
// Complete the countingValleys function below.
int countingValleys(int n, string s) {
int i,sum=0,count;
for(i=0;i<n;i++)
{
if(s[i]=='U')
{
sum+=1;
if(sum==0)
count++;
}
else {
sum-=1;
}
}
return count;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin, s);
int result = countingValleys(n, s);
fout << result << "\n";
fout.close();
return 0;
}
|
code/online_challenges/src/hackerrank/Counting_Valleys/README.md | <b>Problem Link</b>
[Counting Valleys](https://www.hackerrank.com/challenges/counting-valleys/problem)
<b>Description</b>
Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly steps. For every step he took, he noted if it was an uphill, , or a downhill, step. Gary's hikes start and end at sea level and each step up or down represents a unit change in altitude. We define the following terms:
A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.
|
code/online_challenges/src/hackerrank/Electronics_Shop/Electronics_Shop.cpp | // Part of Cosmos by OpenGenus
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
/*
* Complete the getMoneySpent function below.
*/
int getMoneySpent(vector<int> keyboards, vector<int> drives, int b) {
int i,sum=0,j,k=0,ans=-1;
sort(keyboards.begin(),keyboards.end());
sort(drives.begin(),drives.end());
for(i=0;i<keyboards.size();i++)
{
for(j=0;j<drives.size();j++)
{
sum=keyboards[i]+drives[j];
if(sum<=b&&sum>ans)
ans=sum;
}
}
return ans;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string bnm_temp;
getline(cin, bnm_temp);
vector<string> bnm = split_string(bnm_temp);
int b = stoi(bnm[0]);
int n = stoi(bnm[1]);
int m = stoi(bnm[2]);
string keyboards_temp_temp;
getline(cin, keyboards_temp_temp);
vector<string> keyboards_temp = split_string(keyboards_temp_temp);
vector<int> keyboards(n);
for (int keyboards_itr = 0; keyboards_itr < n; keyboards_itr++) {
int keyboards_item = stoi(keyboards_temp[keyboards_itr]);
keyboards[keyboards_itr] = keyboards_item;
}
string drives_temp_temp;
getline(cin, drives_temp_temp);
vector<string> drives_temp = split_string(drives_temp_temp);
vector<int> drives(m);
for (int drives_itr = 0; drives_itr < m; drives_itr++) {
int drives_item = stoi(drives_temp[drives_itr]);
drives[drives_itr] = drives_item;
}
/*
* The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
*/
int moneySpent = getMoneySpent(keyboards, drives, b);
fout << moneySpent << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
|
code/online_challenges/src/hackerrank/Electronics_Shop/Electronics_Shop.java | // Part of Cosmos by OpenGenus
import java.io.*;
import java.util.*;
public class Solution {
/*
* getMoneySpent function to get the total money spent
*/
static int getMoneySpent(int[] keyboards, int[] drives, int b) {
HashMap<Integer, Boolean> ans = new HashMap<>();
for (int i = 0; i < keyboards.length; i++) {
for (int j = 0; j < drives.length; j++) {
if (keyboards[i] + drives[j] <= b) {
ans.put((keyboards[i] + drives[j]), true);
}
}
}
int max = -1;
if (!ans.isEmpty()) {
for (Integer val : ans.keySet()) {
if (val > max) {
max = val;
}
}
}
return max;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] bnm = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");
int b = Integer.parseInt(bnm[0]);
int n = Integer.parseInt(bnm[1]);
int m = Integer.parseInt(bnm[2]);
int[] keyboards = new int[n];
String[] keyboardsItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");
for (int keyboardsItr = 0; keyboardsItr < n; keyboardsItr++) {
int keyboardsItem = Integer.parseInt(keyboardsItems[keyboardsItr]);
keyboards[keyboardsItr] = keyboardsItem;
}
int[] drives = new int[m];
String[] drivesItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");
for (int drivesItr = 0; drivesItr < m; drivesItr++) {
int drivesItem = Integer.parseInt(drivesItems[drivesItr]);
drives[drivesItr] = drivesItem;
}
/*
* The maximum amount of money she can spend on a keyboard and USB
* drive, or -1 if she can't purchase both items.
*/
int moneySpent = getMoneySpent(keyboards, drives, b);
bufferedWriter.write(String.valueOf(moneySpent));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
|
code/online_challenges/src/hackerrank/almost_sorted/README.md | ### Problem Link
[Almost Sorted ](https://www.hackerrank.com/challenges/almost-sorted/problem?h_r=internal-search)
### Description
Determine whether the given array can be sorted by using given operation:
- Swap two elements
- Reverse one sub-segment
|
code/online_challenges/src/hackerrank/almost_sorted/almost_sorted.cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
int n = 0;
int p = 0;
int s, l;
s = l = 0;
int t = 0;
std::cin >> n;
std::vector<int> a(n);
std::vector<int> b(n);
for (int i; i < n; ++i) {
std::cin >> a[i];
b[i] = a[i];
}
std::sort(b.begin(), b.end());
for (int i = 0; i < n; ++i) {
if (b[i] != a[i]) {
++p;
if (t == 0) {
s = i;
++t;
}
else
l = i;
}
}
if (p == 0) {
std::cout << "yes\n";
return 0;
}
else if (p == 2) {
std::cout << "yes"
<< "\n";
std::cout << "swap " << s + 1 << " " << l + 1;
return 0;
}
for (int i = l; i > s;--i) {
if (a[i] > a[i - 1]) {
std::cout << "no\n";
return 0;
}
}
std::cout << "yes \n";
std::cout << "reverse " << s + 1 << " " << l + 1;
return 0;
}
|
code/online_challenges/src/hackerrank/alternating_characters/Alternating.py | count = 0
test_cases = int(input())
def cal(test_cases):
arr = input()
count = 0
for i in range(len(arr)-1):
if arr[i] == arr[i+1]:
count += 1
return count
for i in range(test_cases):
print(cal(test_cases))
|
code/online_challenges/src/hackerrank/alternating_characters/README.md | Description
You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.
Your task is to find the minimum number of required deletions.
|
code/online_challenges/src/hackerrank/array_manipulation/README.md | ### Problem Link
[Array Manipulation](https://www.hackerrank.com/challenges/crush/problem?h_r=internal-search)
### Description
You are given a list of size n, initialized with zeroes. You have to perform m queries on the list and output the maximum of final values of all the n elements in the list. For every query, you are given three integers a, b and k and you have to add value k to all the elements ranging from index a to b(both inclusive).
|
code/online_challenges/src/hackerrank/array_manipulation/array_manipulation.cpp | #include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int n;
int m;
int a;
int b;
int k;
std::cin >> n >> m;
std::vector<std::pair<int, int> > v;
for (int i = 0; i < m; ++i) {
std::cin >> a >> b >> k;
v.push_back(std::make_pair(a, k));
v.push_back(std::make_pair(b + 1, -1 * k));
}
long mx = 0, sum = 0;
std::sort(v.begin(), v.end());
for (int i = 0; i < 2 * m; ++i) {
sum += v[i].second;
mx = std::max(mx, sum);
}
std::cout << mx << "\n";
return 0;
}
|
code/online_challenges/src/hackerrank/bigger_is_greater/README.md | ### Problem Link
[Bigger is Greater](https://www.hackerrank.com/challenges/bigger-is-greater/problem?h_r=internal-search)
### Description
lexicographically higher string possible, example: given the word ABCD, the next largest word is ABDC.
|
code/online_challenges/src/hackerrank/bigger_is_greater/bigger_is_greater.cpp | #include <iostream>
#include <algorithm>
int main()
{
int t;
std::cin >> t;
while (t--) {
std::string s;
std::cin >> s;
bool ans = next_permutation(s.begin(), s.end()); // do permutation and store it in string ans
if (!ans) // if there is no permutation possible original and ans will be same
std::cout << "no answer\n";
else
std::cout << s << "\n"; // else print ans
}
}
|
code/online_challenges/src/hackerrank/dynamic_array/dynamic_array.java | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'dynamicArray' function below.
*
* The function is expected to return an INTEGER_ARRAY. The function accepts
* following parameters: 1. INTEGER n 2. 2D_INTEGER_ARRAY queries
*/
public static List < Integer > dynamicArray(int n, List < List < Integer >> queries) {
List < List < Integer >> seqList = new ArrayList < List < Integer >> ();
List < Integer > seq = new ArrayList < > ();
for (int i = 0; i < n; i++) {
seq = new ArrayList < > ();
seqList.add(seq);
}
ArrayList < Integer > ans = new ArrayList < Integer > ();
int lastAns = 0;
for (int i = 0; i < queries.size(); i++) {
int querynum = queries.get(i).get(0);
int x = queries.get(i).get(1);
int ele = queries.get(i).get(2);
if (querynum == 1) {
seqList.get((x ^ lastAns) % n).add(ele);
} else if (querynum == 2) {
seq = seqList.get((x ^ lastAns) % n);
lastAns = seq.get(ele % seq.size());
ans.add(lastAns);
}
}
return ans;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
int n = Integer.parseInt(firstMultipleInput[0]);
int q = Integer.parseInt(firstMultipleInput[1]);
List < List < Integer >> queries = new ArrayList < > ();
IntStream.range(0, q).forEach(i - > {
try {
queries.add(Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt).collect(toList()));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
List < Integer > result = Result.dynamicArray(n, queries);
bufferedWriter.write(result.stream().map(Object::toString).collect(joining("\n")) + "\n");
bufferedReader.close();
bufferedWriter.close();
}
}
|
code/online_challenges/src/hackerrank/encryption/README.md | ### Problem Link
[Encryption](https://www.hackerrank.com/challenges/encryption/problem?h_r=internal-search)
### Description
Number of rows and the number of columns in the rectangle lie between floor(sqrt(len(word))) and ceil(sqrt(len(word))).
Choose a set of values for rows and columns, out of the 4 available choices.
|
code/online_challenges/src/hackerrank/encryption/encryption.cpp | #include <cmath>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
int r, c;
int l = s.size();
r = floor(sqrt(l));
c = ceil(sqrt(l));
for (int i = 0; i < c; ++i) {
for (int j = i; j < l; j = j + c)
std::cout << s[j];
std::cout << "\n";
}
}
|
code/online_challenges/src/hackerrank/jumping_on_the_clouds/Readme.md | # Problem Link
[Jumping on the Clouds](https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem)
# Description
Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are
thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to
the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number
of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game.
|
code/online_challenges/src/hackerrank/jumping_on_the_clouds/Solution.java | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int c[] = new int[n];
int zero = 0;
int jump = 0;
for(int c_i=0; c_i < n; c_i++){
c[c_i] = in.nextInt();
if(c[c_i]==1) {
jump += zero/2+1;
zero = 0;
}
else
zero ++;
}
jump += zero/2;
System.out.print(jump);
}
}
|
code/online_challenges/src/hackerrank/lonely_integer/lonely_integer.cpp | #include <iostream>
#include <vector>
using namespace std;
vector<string> split_string(string);
// Complete the lonelyinteger function below.
int lonelyinteger(vector<int> a)
{
int unique = 0;
int n = a.size();
for(int i = 0;i < n;++i)
{
unique ^= a[i];
}
return unique;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string a_temp_temp;
getline(cin, a_temp_temp);
vector<string> a_temp = split_string(a_temp_temp);
vector<int> a(n);
for (int i = 0; i < n; ++i) {
int a_item = stoi(a_temp[i]);
a[i] = a_item;
}
int result = lonelyinteger(a);
fout << result << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
|
code/online_challenges/src/hackerrank/the_maximum_subarray/README.md | ### Problem Link
[Maximum Subarray](https://www.hackerrank.com/challenges/maxsubarray/problem)
### Description
Given a integer array, find the maximum subarray sum and the maximum subsequence sum.
[Subarray](https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/)
|
code/online_challenges/src/hackerrank/the_maximum_subarray/the_maximum_subarray.cpp | #include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int t; //t is the number of test case
std::cin >> t;
while (t--) {
int n; //n is the size of input array
int sum, ans, ans1;
sum = ans = ans1 = 0;
int flag = 0;
std::cin >> n;
std::vector<int> arr(n);
for (int i = 0; i < n; ++i) {
std::cin >> arr[i];
if (arr[i] >= 0)
++flag;
}
if (flag == 0) {
std::sort(arr.begin(), arr.end());
std::cout << arr[n - 1] << " " << arr[n - 1] << "\n";
continue;
}
sum = ans = ans1 = 0;
for (int i = 0; i < n; ++i) {
if ((sum + arr[i]) > 0)
sum += arr[i];
else
sum = 0;
if (arr[i] >= 0)
ans1 += arr[i];
ans = std::max(ans, sum);
}
std::cout << ans << " " << ans1 << "\n";
}
return 0;
}
|
code/online_challenges/src/leetcode/Arranging_coins/arranging_coins.cpp | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool possibol(int n, long long row){
long sum = (row*(row+1))/2;
return n>=sum;
}
int arrangeCoins(int n) {
int start=0,end=n,answer=0;
while(start<=end){
int mid=start+(end-start)/2;
if(possibol(n,mid)){
start=mid+1;
answer=mid;
}else{
end=mid-1;
}
}
return answer;
}
};
int main(){
cout<< Solution().arrangeCoins(5) << "\n";
return 0;
}
|
code/online_challenges/src/leetcode/Find_Minimum_in_Rotated_Sorted_Array/FindMinimumInRotatedSortedArray.java | import java.util.*;
/*
*
* https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
*
* Solution Description:
* "Binary Search Approach"
* - Since array is sorted we can apply Binary Search but since array is rotated, we cannot apply Binary search directly.
* - There would be a point in array, elements left to that point are greater than first element and elements right to that point are lesser than first element. we have to find that point.
* Algorithm:
* 1. Find the mid element of the array.
* 2. If mid element > first element of array then we have to search for the inflection point on the right of mid.
* 3. If mid element < first element of array then we have to search for the inflection point on the left of mid.
* 4. We stop our search when we find the inflection point, when either of the two conditions is satisfied:
* (i) nums[mid] > nums[mid + 1] Hence, mid+1 is the smallest, return nums[mid+1].
* (ii) nums[mid - 1] > nums[mid] Hence, mid is the smallest, return nums[mid].
*
* Time Complexity: O(logN)
*
*/
public class FindMinimumInRotatedSortedArray {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int[]arr = new int[T];
for (int i = 0; i < T; i++)
{
arr[i] = sc.nextInt();
}
int result = findMin(arr);
System.out.println(result);
return;
}
public static int findMin(int[] nums) {
// If the array has just one element,then it is the minimum element then return that element.
if (nums.length == 1) {
return nums[0];
}
// initializing left and right pointers.
int left = 0, right = nums.length - 1;
// if the last element is greater than the first element then there is no rotation.
// Hence the smallest element is first element, return first element.
if (nums[right] > nums[0]) {
return nums[0];
}
// Binary search
while(right >= left) {
// Find the mid element
int mid = left + (right - left) / 2;
// if the mid element is greater than its next element, i.e. mid+1 element, which means this point is the inflection point and mid+1 element is the smallest.
// return mid+1 element.
if (nums[mid] > nums[mid + 1]) {
return nums[mid + 1];
}
// if the mid element is lesser than its previous element.i.e. mid-1 element, which means this is the inflection point and mid element is the smallest.
// return mid element.
if (nums[mid - 1] > nums[mid]) {
return nums[mid];
}
// if the mid elements value is greater than the 0th element this means
// the least value is still somewhere to the right as we are still dealing with elements
// greater than nums[0]
if (nums[mid] > nums[0]) {
left = mid + 1;
}
else {
// if nums[0] is greater than the mid value then this means the smallest value is somewhere to
// the left
right = mid - 1;
}
}
return -1;
}
}
|
code/online_challenges/src/leetcode/README.md | # LeetCode
From [LeetCode](https://leetcode.com/)
It's a website where people–mostly software engineers–practice their coding skills. There are 800+ questions (and growing), each with multiple solutions. Questions are ranked by level of difficulty: easy, medium, and hard.
The purpose of LeetCode is to provide you hands-on training on real coding interview questions. The Online Judge gives you immediate feedback on the correctness and efficiency of your algorithm which facilitates a great learning experience.
|
code/online_challenges/src/leetcode/Sqrt(x)/Sqrt(x).cpp | #include<bits/stdc++.h>
using namespace std;
// O(logn)
class Solution {
public:
int mySqrt(int x) {
double start=0,end=x;
for(int i=0;i<100;++i){
double mid = start + (end - start) / 2;
if(mid*mid<=x){
start = mid;
}else{
end = mid;
}
}
return start;
}
};
int main(){
cout<< Solution().mySqrt(8) << "\n";
return 0;
}
|
code/online_challenges/src/leetcode/decode_string/encryption_string.py | # -*- coding: utf-8 -*-
"""
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
"""
class Encryption:
## APPROACH : 2 Stacks
def decodeString(self, string: str) -> str:
## TIME COMPLEXITY : O(N)
## SPACE COMPLEXITY : O(N)
number = []
string = []
num = ""
char = ""
for i, ch in enumerate(string):
if ch.isdigit():
num += ch
elif ch == "[":
number.append(int(num))
string.append(char)
num = ""
char = ""
elif ch == "]":
char = string.pop() + number.pop() * char
else:
char += ch
return char
String_object = Solution()
# testcases
String_object.decodeString("3[a]2[bc]")
String_object.decodeString("3[a2[c]]")
String_object.decodeString("2[abc]3[cd]ef")
String_object.decodeString("abc3[cd]xyz")
|
code/online_challenges/src/leetcode/longest_substring_without_repetition/longest_substring_without_repetition.cpp | /*
*
* Problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/
*
* Solution Description:
* "Sliding Window Approach"
*
* 1. We take two pointers i (left pointer) and j (right pointer).
* 2. We widen our window on the right side at each step (by incrementing j).
* 3. Whenever s[j] has been previously visited, we move the left pointer over
* to the just right of the last visited index of (s[j]). This makes all
* characters in the window from i to j unique again.
* 4. We do a comparison between the current best and the length of the
* window (i - j + 1), and update our solution accordingly.
* 5. When j crosses the size of the string, we stop and we will end up with
* the length of the longset substring without repetition of characters
* as our solution.
*
* Time Complexity: O(N)
*
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
static int lengthOfLongestSubstring(string s) {
int n = s.length();
// Map each character to its last visited index in s
unordered_map<char, int> char_to_index;
int best_len = 0;
for (int i = 0, j = 0; j < n; j++)
{
// Update i if s[j] has been seen before
if (char_to_index.find(s[j]) != char_to_index.end())
i = max(i, char_to_index[s[j]] + 1);
// Length of window = j - i + 1
best_len = max(j - i + 1, best_len);
char_to_index[s[j]] = j;
}
return best_len;
}
};
int main()
{
int T = 3;
string testCases[] = {"abcabcbb", "bbbbb", "pwwkew"};
for (int i = 0; i < T; i++)
{
int sol = Solution::lengthOfLongestSubstring(testCases[i]);
cout << "String: " << testCases[i] << " | Solution: " << sol << endl;
}
return 0;
}
|
code/online_challenges/src/leetcode/max_distance_to_closest_person/Solution.py | '''
Link to the problem: https://leetcode.com/problems/maximize-distance-to-closest-person/
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat,
and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to the closest person.
Example 1:
Input: seats = [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
Example 2:
Input: seats = [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
'''
class Solution:
def maxDistToClosest(self, seats: list()) -> int:
res = 0
n = len(seats)
f_id = seats.index(1)
last = f_id
for i in range(n):
if seats[i] == 1:
res = max(res, (i - last) // 2)
last = i
return max(res, n - last - 1, f_id)
# Creating object for the solution class and invoking the 'maxDistToClosest' function.
obj = Solution()
input = list(map(int, input('Enter the list: ').split(' ')))
res = obj.maxDistToClosest(input)
print(res) |
code/online_challenges/src/leetcode/maximum_subarray/maximumsubarray.cpp | //In this corrected code, we compare max_ending + nums[i] with nums[i] to determine if it's beneficial to extend the current subarray or start a new one. This way, the code correctly calculates the maximum subarray sum.
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len = nums.size();
int max_overall = INT_MIN;
int max_ending = 0;
for (int i = 0; i < len; i++) {
if (max_ending + nums[i] >= nums[i]) {
max_ending += nums[i];
} else {
max_ending = nums[i];
}
if (max_ending > max_overall) {
max_overall = max_ending;
}
}
return max_overall;
}
};
|
code/online_challenges/src/leetcode/median_of_two_sorted_arrays/median_of_two_sorted_arrays.cpp | class Solution
{
public:
double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2)
{
int i = 0, j = 0;
double m;
vector<int> v;
while (i < nums1.size() && j < nums2.size())
{
if (nums1[i] < nums2[j])
{
v.push_back(nums1[i++]);
}
else if (nums1[i] > nums2[j])
{
v.push_back(nums2[j++]);
}
else
{
v.push_back(nums1[i++]);
}
}
while (i < nums1.size())
{
v.push_back(nums1[i++]);
}
while (j < nums2.size())
{
v.push_back(nums2[j++]);
}
for (int i = 0; i < v.size(); ++i)
{
cout << v[i] << " ";
}
int n = v.size();
double r = n % 2 == 0 ? (double)(v[n / 2] + v[n / 2 - 1]) / 2 : v[n / 2];
return r;
}
};
|
code/online_challenges/src/leetcode/minimum_number_of_days_to_make_m_bouquets/minimum_number_of_days_to_make_m_bouquets.cpp | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int minDays(vector<int>& bloomDay, int m, int k) {
if(m > (int)bloomDay.size() / k){
return -1;
}
int start=1,end=*max_element(bloomDay.begin(), bloomDay.end()),res=-1;
while(start<=end){
int mid=start+(end-start)/2;
if(possible(bloomDay,m,k,mid)){
end=mid-1;
res=mid;
}else{
start=mid+1;
}
}
return res;
}
bool possible(vector<int>& bloomDay, int m, int k, int waiting_days){
int adj_flowers=0, bouquets=0;
for(int i=0;i<(int)bloomDay.size();++i){
if(bloomDay[i]<=waiting_days){
++adj_flowers;
if(adj_flowers >= k){
adj_flowers=0;
++bouquets;
}
if(bouquets==m){
return true;
}
}else{
adj_flowers=0;
}
}
return false;
}
};
int main(){
vector<int>bloomDay {1,10,3,10,2};
int m=3;
int k=1;
cout<< Solution().minDays(bloomDay, m ,k) << "\n";
return 0;
}
|
code/online_challenges/src/leetcode/remove_duplicates_from_sorted_list_ii/remove_duplicates_from_sorted_list_ii.cpp | /*
link to problem:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
difficulty level: Medium
approach:
maintained a previous,current and next pointer in the linked list
if next pointer and curr pointer is having same value then we increment the next pointer till they are unequal or nex becomes NULL
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL)
return head;
ListNode *curr = head;
ListNode *nex;
ListNode *prev = NULL;
while (curr != NULL)
{
nex = curr->next;
cout << curr->val;
if (nex != NULL and curr->val == nex->val)
{
while (nex != NULL && nex->val == curr->val)
{
nex = nex->next;
}
if (nex != NULL)
{
curr->next = nex->next;
swap(curr->val, nex->val);
// curr=curr->next;
}
else
{
if (head == curr)
head = NULL;
if (prev != NULL)
{
prev->next = NULL;
}
curr = NULL;
}
}
else
{
prev = curr;
curr = curr->next;
}
}
return head;
}
}; |
code/online_challenges/src/leetcode/symmetric_tree/symmetric_tree.cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
bool isMirror(TreeNode *left, TreeNode *right)
{
return (!left && left == right) ||
(left && right && left->val == right->val && isMirror(left->left, right->right) && isMirror(left->right, right->left));
}
bool isSymmetric(TreeNode *root)
{
return !root || isMirror(root->left, root->right);
}
};
|
code/online_challenges/src/leetcode/two_sum/two_sum.cpp | #include<bits/stdc++.h>
using namespace std;
//O(n^2)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target){
vector<int>res;
for(int i=0;i<(int)nums.size();++i){
for(int j=i+1;j<(int)nums.size();++j){
if(nums[i]+nums[j]==target){
res.push_back(i);
res.push_back(j);
return res;
}
}
}
return res;
}
};
int main(){
vector<int>numbers {2,7,11,15};
vector<int>result;
result = Solution().twoSum(numbers, 9);
for(int i=0;i<(int)result.size();++i){
cout<<result[i]<< " ";
}
return 0;
}
|
code/online_challenges/src/project_euler/README.md | # Project Euler
From [Project Euler](https://projecteuler.net/):
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.
This folder provides solutions to Project Euler problems, in a variety of languages
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/online_challenges/src/project_euler/documentation_guide.md | # Documentation Guide
## README Template
When you are adding a new folder for a new Project Euler problem, add a README.md in the folder with the following format:
```Markdown
# Project Euler Problem #NUM: Title of Problem
([Problem Link](<- Is alt text. This is the actual Link to the problem))
Problem text copy/pasted exactly as it is from official website.
If there is center alignment, or formatting in the original question, then update as equivalent here.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
```
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/online_challenges/src/project_euler/problem_001/README.md | # Project Euler Problem #001: Multiples of 3 and 5
([Problem Link](https://projecteuler.net/problem=1))
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/online_challenges/src/project_euler/problem_001/problem_001.c | #include <stdio.h>
int
main(void)
{
int sum, i;
for (i = 0; i < 1000; ++i)
sum += (i % 3 == 0) || (i % 5 == 0) ? i : 0;
printf("%d\n", sum);
} |
code/online_challenges/src/project_euler/problem_001/problem_001.cpp | #include <iostream>
int main()
{
int sum;
for (int i = 0; i < 1000; ++i)
sum += (i % 3 == 0) || (i % 5 == 0) ? i : 0;
std::cout << sum << "\n";
}
|
code/online_challenges/src/project_euler/problem_001/problem_001.java | public class Problem001 {
public static void main(String []args) {
int sum = 0;
for(int i = 1; i < 1000; i++)
sum += (i % 3 ==0 || i % 5 == 0) ? i : 0;
System.out.print(sum);
}
}
|
code/online_challenges/src/project_euler/problem_001/problem_001.js | let sum = 0;
for (let i = 0; i < 1000; i += 1) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
}
console.log(sum);
|
code/online_challenges/src/project_euler/problem_001/problem_001.py | def main():
total = 0
for i in range(0, 1000):
total += i if (i % 3 == 0) or (i % 5 == 0) else 0
print(total)
if __name__ == "__main__":
main()
|
code/online_challenges/src/project_euler/problem_001/problem_001.rs | fn main() {
let mut sum = 0;
for i in 1..1000 {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
println!("{}", sum);
}
|
code/online_challenges/src/project_euler/problem_002/README.md | # Project Euler Problem #002: Even Fibonacci numbers
([Problem Link](https://projecteuler.net/problem=2))
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
<p align="center">
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
</p>
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/online_challenges/src/project_euler/problem_002/problem_002.c | #include <stdio.h>
int
main(void)
{
/* Variables to keep track of Fibonacci numbers */
int p2 = 0;
int p1 = 0;
int current = 1;
int sum = 0;
while (current <= 4000000) {
/* Add even fibonacci numbers */
sum += (current % 2 == 0) ? current : 0;
/* Update fibonacci numbers */
p2 = p1;
p1 = current;
current = p2 + p1;
}
printf("%d\n", sum);
} |
code/online_challenges/src/project_euler/problem_002/problem_002.cpp | #include <iostream>
int main()
{
// Variables to keep track of Fibonacci numbers
int p2 = 0;
int p1 = 0;
int current = 1;
int sum = 0;
while (current <= 4000000)
{
// Add even fibonacci numbers
sum += (current % 2 == 0) ? current : 0;
// Update fibonacci numbers
p2 = p1;
p1 = current;
current = p2 + p1;
}
std::cout << sum << "\n";
}
|
code/online_challenges/src/project_euler/problem_002/problem_002.java | public class Problem002 {
public static void main(String[] args) {
int sum = 0;
int first = 0;
int second = 1;
int third = 0;
while(third < 4000000) {
third = first + second;
sum += (third % 2 == 0) ? third : 0;
first = second;
second = third;
}
System.out.println(sum);
}
}
|
code/online_challenges/src/project_euler/problem_002/problem_002.js | let sum = 0;
let num1 = 0;
let num2 = 0;
let current = 1;
while (current < 4000000) {
sum += current % 2 === 0 ? current : 0;
num2 = num1;
num1 = current;
current = num2 + num1;
}
console.log(sum);
|
code/online_challenges/src/project_euler/problem_002/problem_002.py | def main():
# Variables to keep track of Fibonacci numbers
p2 = 0
p1 = 0
current = 1
total = 0
while current <= 4000000:
# Add even fibonacci numbers
total += current if current % 2 == 0 else 0
# Update fibonacci numbers
p2 = p1
p1 = current
current = p2 + p1
print(total)
if __name__ == "__main__":
main()
|
code/online_challenges/src/project_euler/problem_003/README.md | # Project Euler Problem #003: Largest prime factor
([Problem Link](https://projecteuler.net/problem=3))
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/online_challenges/src/project_euler/problem_003/problem_003.c | #include <stdio.h>
int
main(void)
{
long long int n = 600851475143;
long long int h = 0;
long long int c = 2;
while (n != 1) {
if ((n % c == 0) && (c > h)) {
h = c;
n /= c;
}
++c;
}
printf("%lld\n", h);
} |
code/online_challenges/src/project_euler/problem_003/problem_003.cpp | #include <iostream>
#include <vector>
#include <cmath>
int main()
{
long long int n = 600851475143;
long long int h = 0;
long long int c = 2;
while (n != 1)
{
if ((n % c == 0) && (c > h))
{
h = c;
n /= c;
}
++c;
}
std::cout << h << "\n";
}
|
code/online_challenges/src/project_euler/problem_003/problem_003.java | public class Problem003 {
public static long smallestFactor(long n) {
if (n <= 1)
throw new IllegalArgumentException();
for (long i = 2 ,end = (long)Math.sqrt(n); i <= end; i++) {
if (n % i == 0)
return i;
}
return n;
}
public static void main(String []args) {
long n = 600851475143L;
long big = 1;
while(big != n) {
big = smallestFactor(n);
if (big < n)
n /= big;
else
System.out.println(big);
}
}
}
|
code/online_challenges/src/project_euler/problem_003/problem_003.js | let num = 600851475143;
let highestPrimeFactor = 0;
let currentFactor = 2;
while (num > highestPrimeFactor) {
if (num % currentFactor === 0) {
highestPrimeFactor = currentFactor;
num /= currentFactor;
} else {
++currentFactor;
}
}
console.log(highestPrimeFactor);
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.