Instruction
stringlengths 261
35k
| Response
stringclasses 1
value |
---|---|
For this Question: There has been an attack on SHIELD. Nick Fury has given you the responsibility of protecting all the information but during the chaos he forgot to tell you how to login into the classified information. Just then a “secret code” appears on the screen.
Print the information in a 2D integer array of size (N x M) in a spiral form. That is, you need to print in the order followed for every iteration:
a. First row(left to right)
b. Last column(top to bottom)
c. Last row(right to left)
d. First column(bottom to top)
Mind that every element will be printed only once.The first line of input contains two integers N and M, the next N lines of input contains M space- separated integers each depicting the values of the matrix.
Constraints:-
2 <= N, M <= 500
1 <= Matrix[][] <= 1000000Print the matrix in spiral form as shown in the example.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
1 2 3 6 9 8 7 4 5
Sample Input:-
4 5
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
Sample Output:-
2 4 6 8 10 20 30 40 38 36 34 32 22 12 14 16 18 28 26 24, I have written this Solution Code: def spiralPrint(m, n, a):
k = 0
l = 0
''' k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator '''
while (k < m and l < n):
for i in range(l, n):
print(a[k][i], end=" ")
k += 1
for i in range(k, m):
print(a[i][n - 1], end=" ")
n -= 1
if (k < m):
for i in range(n - 1, (l - 1), -1):
print(a[m - 1][i], end=" ")
m -= 1
if (l < n):
for i in range(m - 1, k - 1, -1):
print(a[i][l], end=" ")
l += 1
n,m = map(int,input().split())
arr=[]
for i in range(0,n):
a = list(map(int,input().split()))
arr.append(a)
spiralPrint(n,m,arr), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There has been an attack on SHIELD. Nick Fury has given you the responsibility of protecting all the information but during the chaos he forgot to tell you how to login into the classified information. Just then a “secret code” appears on the screen.
Print the information in a 2D integer array of size (N x M) in a spiral form. That is, you need to print in the order followed for every iteration:
a. First row(left to right)
b. Last column(top to bottom)
c. Last row(right to left)
d. First column(bottom to top)
Mind that every element will be printed only once.The first line of input contains two integers N and M, the next N lines of input contains M space- separated integers each depicting the values of the matrix.
Constraints:-
2 <= N, M <= 500
1 <= Matrix[][] <= 1000000Print the matrix in spiral form as shown in the example.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
1 2 3 6 9 8 7 4 5
Sample Input:-
4 5
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
Sample Output:-
2 4 6 8 10 20 30 40 38 36 34 32 22 12 14 16 18 28 26 24, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int a[][] = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
a[i][j]=sc.nextInt();
}
}
int k=0,l=0;
int i;
while(k < m && l < n){
for (i = l; i < n; ++i) {
System.out.print(a[k][i]+" ");
}
k++;
for (i = k; i < m; ++i) {
System.out.print(a[i][n-1]+" ");
}
n--;
if (k < m) {
for (i = n - 1; i >= l; --i) {
System.out.print(a[m-1][i]+" ");
}
m--;
}
if (l < n) {
for (i = m - 1; i >= k; --i) {
System.out.print(a[i][l]+" ");
}
l++;
}
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There has been an attack on SHIELD. Nick Fury has given you the responsibility of protecting all the information but during the chaos he forgot to tell you how to login into the classified information. Just then a “secret code” appears on the screen.
Print the information in a 2D integer array of size (N x M) in a spiral form. That is, you need to print in the order followed for every iteration:
a. First row(left to right)
b. Last column(top to bottom)
c. Last row(right to left)
d. First column(bottom to top)
Mind that every element will be printed only once.The first line of input contains two integers N and M, the next N lines of input contains M space- separated integers each depicting the values of the matrix.
Constraints:-
2 <= N, M <= 500
1 <= Matrix[][] <= 1000000Print the matrix in spiral form as shown in the example.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
1 2 3 6 9 8 7 4 5
Sample Input:-
4 5
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
Sample Output:-
2 4 6 8 10 20 30 40 38 36 34 32 22 12 14 16 18 28 26 24, I have written this Solution Code:
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 1001
#define MOD 1000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
signed main(){
int m,n;
cin>>m>>n;
int a[m][n];
FOR(i,m){
FOR(j,n){
cin>>a[i][j];}
}
int k=0,l=0;
int i;
while(k < m && l < n){
for (i = l; i < n; ++i) {
cout << a[k][i] << " ";
}
k++;
for (i = k; i < m; ++i) {
cout << a[i][n - 1] << " ";
}
n--;
if (k < m) {
for (i = n - 1; i >= l; --i) {
cout << a[m - 1][i] << " ";
}
m--;
}
if (l < n) {
for (i = m - 1; i >= k; --i) {
cout << a[i][l] << " ";
}
l++;
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a singly linked list of size <b>N</b>, and an integer <b>K</b>. You need to <b>swap the Kth node from beginning and Kth node from end</b> in linked list.
<b>Note:</b> You need to swap the nodes through the links and not changing the content of the nodes.First line of input contains the number of testcases T.
The first line of every testacase contains N, number of nodes in linked list and K, the nodes to be swapped and the second line of contains the elements of the linked list.
<b>User task:</b>
The task is to complete the function swapkthnode(), which has arguments head, num(no of nodes) and K, and it should return new head. The validation is done internally by the driver code to ensure that the swapping is done by changing references/pointers only. A correct code would always cause output as 1.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^3
1 <= K <= 10^3For each testcase, if the nodes are swapped correctly, the output will be <b>1</b>, else <b>0</b>.Input:
3
4 1
1 2 3 4
5 3
1 2 3 4 5
4 4
1 2 3 4
Output:
1
1
1
Explanation:
Testcase 1: Here K = 1, hence after swapping the 1st node from beginning and end the new list will be 4 2 3 1.
Testcase 2: Here k = 3, hence after swapping the 3rd node from beginning and end the new list will be 1 2 3 4 5.
Testcase 3: Here k = 4, hence after swapping the 4th node from beginning and end the new list will be 4 2 3 1., I have written this Solution Code: // Should swap Kth node from beginning and Kth
// node from end in list and return new head.
static Node swapkthnode(Node head, int num, int K)
{
if(K > num) return head;
if(2*K-1 == num) return head;
Node x_prev = null;
Node x = head;
Node y_prev = null;
Node y = head;
int count = K-1;
while(count-- > 0){
x_prev = x;
x = x.next;
}
count = num - K;
while(count-- > 0){
y_prev = y;
y = y.next;
}
if(x_prev != null)
x_prev.next = y;
if(y_prev != null)
y_prev.next = x;
Node temp = x.next;
x.next = y.next;
y.next = temp;
if(K == 1)
head = y;
if(K == num)
head = x;
return head;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N and an integer K, Your task is to multiply the first leftmost digit of the number to the number itself. You have to repeat this process K times.
For eg:- if N=3 and K=5 then:
3 * 3 = 9
9 * 9 = 81
81 * 8 = 648
648 * 6 = 3888
3888 * 3 = 11664<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>KOperations()</b> that takes the integer N as parameter.
<b>Constraints:</b>
1 <= N <= 100
1 <= K <= 10^9Return the Number after K operations
<b>Note:</b> It is guaranteed that the output will always be less than 10^17.Sample Input:-
3 5
Sample Output:-
11664
Explanation:- See problem statement for explanation.
Sample Input:-
22 2
Sample Output:-
176, I have written this Solution Code:
long long KOperations(long long N, long long K){
long long p;
while(K--){
p=N;
while(p>=10){
p=p/10;
}
if(p==1){return N;}
N*=p;
}
return N;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N and an integer K, Your task is to multiply the first leftmost digit of the number to the number itself. You have to repeat this process K times.
For eg:- if N=3 and K=5 then:
3 * 3 = 9
9 * 9 = 81
81 * 8 = 648
648 * 6 = 3888
3888 * 3 = 11664<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>KOperations()</b> that takes the integer N as parameter.
<b>Constraints:</b>
1 <= N <= 100
1 <= K <= 10^9Return the Number after K operations
<b>Note:</b> It is guaranteed that the output will always be less than 10^17.Sample Input:-
3 5
Sample Output:-
11664
Explanation:- See problem statement for explanation.
Sample Input:-
22 2
Sample Output:-
176, I have written this Solution Code:
long long int KOperations(long long N, long long K){
long long int p;
while(K--){
p=N;
while(p>=10){
p=p/10;
}
if(p==1){return N;}
N*=p;
}
return N;
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N and an integer K, Your task is to multiply the first leftmost digit of the number to the number itself. You have to repeat this process K times.
For eg:- if N=3 and K=5 then:
3 * 3 = 9
9 * 9 = 81
81 * 8 = 648
648 * 6 = 3888
3888 * 3 = 11664<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>KOperations()</b> that takes the integer N as parameter.
<b>Constraints:</b>
1 <= N <= 100
1 <= K <= 10^9Return the Number after K operations
<b>Note:</b> It is guaranteed that the output will always be less than 10^17.Sample Input:-
3 5
Sample Output:-
11664
Explanation:- See problem statement for explanation.
Sample Input:-
22 2
Sample Output:-
176, I have written this Solution Code: public static long KOperations(long N, long K){
long p=N;
while(K-->0){
p=N;
while(p>=10){
p=p/10;
}
if(p==1){return N;}
N=N*p;
}
return N;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N and an integer K, Your task is to multiply the first leftmost digit of the number to the number itself. You have to repeat this process K times.
For eg:- if N=3 and K=5 then:
3 * 3 = 9
9 * 9 = 81
81 * 8 = 648
648 * 6 = 3888
3888 * 3 = 11664<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>KOperations()</b> that takes the integer N as parameter.
<b>Constraints:</b>
1 <= N <= 100
1 <= K <= 10^9Return the Number after K operations
<b>Note:</b> It is guaranteed that the output will always be less than 10^17.Sample Input:-
3 5
Sample Output:-
11664
Explanation:- See problem statement for explanation.
Sample Input:-
22 2
Sample Output:-
176, I have written this Solution Code:
def KOperations(N,K) :
# Final result of summation of divisors
while K>0 :
p=N
while(p>=10):
p=p/10
if(int(p)==1):
return N;
N=N*int(p)
K=K-1
return N;
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N and F(N) find value of F(1), if, F(i)=(F(i-1) + F(i-1))%1000000007 and 0 <= F(1) < 1000000007.First and the only line of input contains two integers N and F(N).
Constraints:
1 <= N <= 1000000000
0 <= F(N) < 1000000007Print a single integer, F(1).Sample Input 1
2 6
Sample Output 1
3
Exlpanation: F(1) = 3, F(2)=(3+3)%1000000007 = 6.
Sample Input 2
3 6
Sample Input 2
500000005
Explanation:
F(1) = 500000005
F(2) = (500000005+500000005)%1000000007 = 3
F(3)= (3+3)%1000000007 = 6, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
int n=Integer.parseInt(st.nextToken());
int fn=Integer.parseInt(st.nextToken());
long ans=fn;
int P=1000000007;
long inv2n=(long)pow(pow(2,n-1,P)%P,P-2,P);
ans=((ans%P)*(inv2n%P))%P;
System.out.println((ans)%P);
}
static long pow(long x, long y,long P)
{
long res = 1l;
while (y > 0)
{
if ((y & 1) == 1)
res = (res * x)%P;
y = y >> 1;
x = (x * x)%P;
}
return res;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N and F(N) find value of F(1), if, F(i)=(F(i-1) + F(i-1))%1000000007 and 0 <= F(1) < 1000000007.First and the only line of input contains two integers N and F(N).
Constraints:
1 <= N <= 1000000000
0 <= F(N) < 1000000007Print a single integer, F(1).Sample Input 1
2 6
Sample Output 1
3
Exlpanation: F(1) = 3, F(2)=(3+3)%1000000007 = 6.
Sample Input 2
3 6
Sample Input 2
500000005
Explanation:
F(1) = 500000005
F(2) = (500000005+500000005)%1000000007 = 3
F(3)= (3+3)%1000000007 = 6, I have written this Solution Code: n,f=map(int,input().strip().split())
mod=10**9+7
m1=pow(2,n-1,mod)
m=pow(m1,mod-2,mod)
print(f*m%mod), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N and F(N) find value of F(1), if, F(i)=(F(i-1) + F(i-1))%1000000007 and 0 <= F(1) < 1000000007.First and the only line of input contains two integers N and F(N).
Constraints:
1 <= N <= 1000000000
0 <= F(N) < 1000000007Print a single integer, F(1).Sample Input 1
2 6
Sample Output 1
3
Exlpanation: F(1) = 3, F(2)=(3+3)%1000000007 = 6.
Sample Input 2
3 6
Sample Input 2
500000005
Explanation:
F(1) = 500000005
F(2) = (500000005+500000005)%1000000007 = 3
F(3)= (3+3)%1000000007 = 6, I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
long long powerm(long long x, unsigned long long y, long long p)
{
long long res = 1;
x = x % p;
while (y > 0)
{
if (y & 1)
res = (res*x) % p;
y = y>>1;
x = (x*x) % p;
}
return res;
}
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n,fn;
cin>>n>>fn;
int mo=1000000007;
cout<<(fn*powerm(powerm(2,n-1,mo),mo-2,mo))%mo;
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: When learning a new language, we first learn to output some message. Here, we'll start with the famous "Hello World" message. There is no input, you just have to print "Hello World".No InputHello WorldExplanation:
Hello World is printed., I have written this Solution Code: a="Hello World"
print(a), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: When learning a new language, we first learn to output some message. Here, we'll start with the famous "Hello World" message. There is no input, you just have to print "Hello World".No InputHello WorldExplanation:
Hello World is printed., I have written this Solution Code: import java.util.*;
import java.io.*;
class Main{
public static void main(String args[]){
System.out.println("Hello World");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] of size N containing 0s and 1s only. The task is to count the subarrays having an equal number of 0s and 1s.The first line of the input contains an integer N denoting the size of the array and the second line contains N space-separated 0s and 1s.
Constraints:-
1 <= N <= 10^6
0 <= A[i] <= 1For each test case, print the count of required sub-arrays in new line.Sample Input
7
1 0 0 1 0 1 1
Sample Output
8
The index range for the 8 sub-arrays are:
(0, 1), (2, 3), (0, 3), (3, 4), (4, 5)
(2, 5), (0, 5), (1, 6), I have written this Solution Code: size = int(input())
givenList = list(map(int,input().split()))
hs = {}
sm = 0
ct = 0
for i in givenList:
if i == 0:
i = -1
sm = sm + i
if sm == 0:
ct += 1
if sm not in hs.keys():
hs[sm] = 1
else:
freq = hs[sm]
ct = ct +freq
hs[sm] = freq + 1
print(ct), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] of size N containing 0s and 1s only. The task is to count the subarrays having an equal number of 0s and 1s.The first line of the input contains an integer N denoting the size of the array and the second line contains N space-separated 0s and 1s.
Constraints:-
1 <= N <= 10^6
0 <= A[i] <= 1For each test case, print the count of required sub-arrays in new line.Sample Input
7
1 0 0 1 0 1 1
Sample Output
8
The index range for the 8 sub-arrays are:
(0, 1), (2, 3), (0, 3), (3, 4), (4, 5)
(2, 5), (0, 5), (1, 6), I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define max1 1000001
int a[max1];
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
if(a[i]==0){a[i]=-1;}
}
long sum=0;
unordered_map<long,int> m;
long cnt=0;
for(int i=0;i<n;i++){
sum+=a[i];
if(sum==0){cnt++;}
cnt+=m[sum];
m[sum]++;
}
cout<<cnt;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] of size N containing 0s and 1s only. The task is to count the subarrays having an equal number of 0s and 1s.The first line of the input contains an integer N denoting the size of the array and the second line contains N space-separated 0s and 1s.
Constraints:-
1 <= N <= 10^6
0 <= A[i] <= 1For each test case, print the count of required sub-arrays in new line.Sample Input
7
1 0 0 1 0 1 1
Sample Output
8
The index range for the 8 sub-arrays are:
(0, 1), (2, 3), (0, 3), (3, 4), (4, 5)
(2, 5), (0, 5), (1, 6), I have written this Solution Code: import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
// Your code here
Scanner sc = new Scanner(System.in);
int arrSize = sc.nextInt();
long arr[] = new long[arrSize];
for(int i = 0; i < arrSize; i++)
arr[i] = sc.nextInt();
System.out.println(countSubarrays(arr, arrSize));
}
static long countSubarrays(long arr[], int arrSize)
{
for(int i = 0; i < arrSize; i++)
{
if(arr[i] == 0)
arr[i] = -1;
}
long ans = 0;
long sum = 0;
HashMap<Long, Integer> hash = new HashMap<>();
for(int i = 0; i < arrSize; i++)
{
sum += arr[i];
if(sum == 0)
ans++;
if(hash.containsKey(sum) == true)
{
ans += hash.get(sum);
int freq = hash.get(sum);
hash.put(sum, freq+1);
}
else hash.put(sum, 1);
}
return ans;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a side of a square, your task is to calculate and print its area.The first line of the input contains the side of the square.
<b>Constraints:</b>
1 <= side <=100You just have to print the area of a squareSample Input:-
3
Sample Output:-
9
Sample Input:-
6
Sample Output:-
36, I have written this Solution Code: def area(side_of_square):
print(side_of_square*side_of_square)
def main():
N = int(input())
area(N)
if __name__ == '__main__':
main(), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a side of a square, your task is to calculate and print its area.The first line of the input contains the side of the square.
<b>Constraints:</b>
1 <= side <=100You just have to print the area of a squareSample Input:-
3
Sample Output:-
9
Sample Input:-
6
Sample Output:-
36, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int side = Integer.parseInt(br.readLine());
System.out.print(side*side);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Our five power rangers have powers P1, P2, P3, P4, and P5.
To ensure the proper distribution of power, the power of every power ranger must remain <b>less</b> than the sum of powers of other power rangers.
If the above condition is not met, there's an emergency. Can you let us know if there's an emergency?The first and the only line of input contains 5 integers P1, P2, P3, P4, and P5.
Constraints
0 <= P1, P2, P3, P4, P5 <= 100Output "SPD Emergency" (without quotes) if there's an emergency, else output "Stable".Sample Input
1 2 3 4 5
Sample Output
Stable
Explanation
The power of every power ranger is less than the sum of powers of other power rangers.
Sample Input
1 2 3 4 100
Sample Output
SPD Emergency
Explanation
The power of the 5th power ranger (100) is not less than the sum of powers of other power rangers (1+2+3+4=10)., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
int[] arr=new int[5];
BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
String[] s=rd.readLine().split(" ");
int sum=0;
for(int i=0;i<5;i++){
arr[i]=Integer.parseInt(s[i]);
sum+=arr[i];
}
int i=0,j=arr.length-1;
boolean isEmergency=false;
while(i<=j)
{
int temp=arr[i];
sum-=arr[i];
if(arr[i]>= sum)
{
isEmergency=true;
break;
}
sum+=temp;
i++;
}
if(isEmergency==false)
{
System.out.println("Stable");
}
else
{
System.out.println("SPD Emergency");
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Our five power rangers have powers P1, P2, P3, P4, and P5.
To ensure the proper distribution of power, the power of every power ranger must remain <b>less</b> than the sum of powers of other power rangers.
If the above condition is not met, there's an emergency. Can you let us know if there's an emergency?The first and the only line of input contains 5 integers P1, P2, P3, P4, and P5.
Constraints
0 <= P1, P2, P3, P4, P5 <= 100Output "SPD Emergency" (without quotes) if there's an emergency, else output "Stable".Sample Input
1 2 3 4 5
Sample Output
Stable
Explanation
The power of every power ranger is less than the sum of powers of other power rangers.
Sample Input
1 2 3 4 100
Sample Output
SPD Emergency
Explanation
The power of the 5th power ranger (100) is not less than the sum of powers of other power rangers (1+2+3+4=10)., I have written this Solution Code: arr = list(map(int,input().split()))
m = sum(arr)
f=[]
for i in range(len(arr)):
s = sum(arr[:i]+arr[i+1:])
if(arr[i]<s):
f.append(1)
else:
f.append(0)
if(all(f)):
print("Stable")
else:
print("SPD Emergency"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Our five power rangers have powers P1, P2, P3, P4, and P5.
To ensure the proper distribution of power, the power of every power ranger must remain <b>less</b> than the sum of powers of other power rangers.
If the above condition is not met, there's an emergency. Can you let us know if there's an emergency?The first and the only line of input contains 5 integers P1, P2, P3, P4, and P5.
Constraints
0 <= P1, P2, P3, P4, P5 <= 100Output "SPD Emergency" (without quotes) if there's an emergency, else output "Stable".Sample Input
1 2 3 4 5
Sample Output
Stable
Explanation
The power of every power ranger is less than the sum of powers of other power rangers.
Sample Input
1 2 3 4 100
Sample Output
SPD Emergency
Explanation
The power of the 5th power ranger (100) is not less than the sum of powers of other power rangers (1+2+3+4=10)., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d", &x)
#define sz(v) (int) v.size()
#define pr(v) For(i, 0, sz(v)) {cout<<v[i]<<" ";} cout<<endl;
#define slld(x) scanf("%lld", &x)
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(int i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define pb push_back
#define ll long long
#define ld long double
#define int long long
#define double long double
#define mp make_pair
#define F first
#define S second
typedef pair<int, int> pii;
typedef vector<int> vi;
#define pi 3.141592653589793238
const int MOD = 1e9+7;
const int INF = 1LL<<60;
const int N = 2e5+5;
// it's swapnil07 ;)
#ifdef SWAPNIL07
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cout << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
int begtime = clock();
#define end_routine() cout << "\n\nTime elapsed: " << (clock() - begtime)*1000/CLOCKS_PER_SEC << " ms\n\n";
#else
#define endl '\n'
#define trace(...)
#define end_routine()
#endif
void solve(){
vector<int> vect(5);
int tot = 0;
for(int i=0; i<5; i++){
cin>>vect[i];
tot += vect[i];
}
sort(all(vect));
tot -= vect[4];
if(vect[4] >= tot){
cout<<"SPD Emergency";
}
else{
cout<<"Stable";
}
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t=1;
// cin>>t;
while(t--){
solve();
cout<<"\n";
}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Newton recently discovered his fourth law of motion, and the cunning Keppler has stolen his research and is planning to publish it before Newton. But Newton has encrypted his research with a unique key, and Keppler doesn't know the key, but he knows that the key is the answer to the following problem. Can you help Keppler get his hands on the key? The problem is as follows:
You are given the weights of M different planets and have to place them in N orbits around the Sun. The i<sup>th</sup> orbit is at a distance of i light years from the Sun. However, in any single orbit, you can place at most one planet; otherwise, the solar system will collapse. The weight of the i<sup>th</sup> planet is w<sub>i</sub>.
Assume you have placed the i<sup>th</sup> planet on the orbit at distance d<sub>i</sub> from the Sun, where 1 ≤ i ≤ M and d<sub>i</sub>≠d<sub>j</sub> for i≠j. The stability of the Solar System is given by the summation of abs(d<sub>i</sub>-d<sub>j</sub>)w<sub>i</sub>w<sub>j</sub> over all pairs (i, j) such that 1 ≤ i < j ≤ M. Here, abs(x) denotes the absolute value of the integer x. Your goal is to place the planets in such a way that the stability of the Solar System is maximized.
Formally, you have to choose M different positions for the M weights in an array of size N. Assume you have placed the i<sup>th</sup> weight in d<sub>i</sub><sup>th</sup> position, where d<sub>i</sub>≠d<sub>j</sub> for i≠j. Then, the stability of the array is defined as the summation of abs(d<sub>i</sub>-d<sub>j</sub>)w<sub>i</sub>w<sub>j</sub> over all pairs (i, j) such that 1 ≤ i < j ≤ M. You have to find the maximum stability over all possible arrangements.
Using Newton's glorious research, can you help Keppler find this value and become famous?The first line of the input contains two space-separated integers N and M, denoting the number of orbits and number of planets, respectively.
In the next M lines, the i<sup>th</sup> line contains a single integer w<sub>i</sub>, denoting the weight of the i<sup>th</sup> planet.
<b>Constraints:</b>
2 ≤ N ≤ 10<sup>6</sup>
2 ≤ M ≤ min(N,100)
1 ≤ w<sub>i</sub> ≤ 5000
Print a single integer, the maximum stability over all possible arrangements.
Sample Input 1:
2 2
1
3
Sample Output 1:
3
Explanation:
Put the first planet in first orbit and the second in the second orbit. Then stability = (2-1)*1*3 = 3.
Sample Input 2:
4 2
5
6
Sample Output 2:
90
, I have written this Solution Code: #include <algorithm>
#include <iostream>
#include <limits>
#include <numeric>
#include <vector>
constexpr long long inf = std::numeric_limits<long long>::max() / 2;
constexpr int X = 5000;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n, m;
std::cin >> n >> m;
std::vector<int> p(m);
for (auto &e : p) std::cin >> e;
std::sort(p.begin(), p.end(), std::greater<int>());
long long s = std::accumulate(p.begin(), p.end(), 0);
long long cs = 0;
std::vector<long long> pd { 0 };
for (int v : p) {
cs += v;
int m1 = pd.size() - 1;
int m2 = m1 + v;
std::vector<long long> dp(m2 + 1, -inf);
for (int ls = 0; ls <= m1; ++ls) {
{
int nls = ls + v;
dp[nls] = std::max(dp[nls], pd[ls] + nls * (s - nls));
}
{
int nls = ls;
int rs = cs - nls;
dp[nls] = std::max(dp[nls], pd[ls] + rs * (s - rs));
}
}
pd.swap(dp);
}
int siz = pd.size() - 1;
for (int ls = 0; ls <= siz; ++ls) {
pd[ls] += (long long) (n - m - 1) * ls * (s - ls);
}
std::cout << *std::max_element(pd.begin(), pd.end()) << std::endl;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Newton is currently standing at the origin (0, 0), at time t = 0. Each second, he will move exactly 1 unit up, down, left or right from his current position, where each direction has equal probability. Define f(x, y) as follows:
f(x, y) = 0, if the point (x, y) has been visited less than K times upto and including time t = N.
f(x, y) = t<sub>P</sub>, if the point (x, y) has been visited K or more times upto and including time t = N, and t<sub>P</sub> is the time it was visited for the P<sup>th</sup> time (P ≤ K).
Let S be the sum of f(x, y) over all lattice points of the plane. You will be given Q queries to solve. In each query, you are given the integers N and P, and you have to print the expected value of S modulo 998244353. Note that the integer K is constant for all queries.
Formally, it can be shown that the answer to each query can be expressed as an irreducible fraction <sup>p</sup>⁄<sub>q</sub>, where p and q are integers and gcd(q, 998244353) = 1. You have to output the integer equal to pq<sup>-1</sup> mod 998244353 for each query.
Note that the time of first visit of origin is considered to be 0.The first line of the input contains two space separated integers K (1 ≤ K ≤ 10<sup>5</sup>) and Q (1 ≤ Q ≤ 10<sup>5</sup>).
Then Q lines follow, each line containing two integers N and P for each query (1 ≤ P ≤ K ≤ N ≤ 10<sup>5</sup>).Print Q lines — each line containing a single integer with the i<sup>th</sup> line denoting the expected value of S modulo 998244353 for the i<sup>th</sup> query.Sample input 1:
1 1
2 1
Sample output 1:
499122179
Explanation 1:
The value comes out to be 5/2.
Sample input 2:
2 2
3 2
3 1
Sample Output 2:
748683266
748683265, I have written this Solution Code: // define asc
//#define dbg_local
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename t>
using ordered_set = tree<t, null_type, less<t>, rb_tree_tag, tree_order_statistics_node_update>;
// #pragma gcc optimize("ofast")
// #pragma gcc target("avx,avx2,fma")
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define endl '\n'
#define fi first
#define se second
// const int mod = 1e9 + 7;
const int mod=998'244'353;
const long long INF = 2e18 + 10;
// const int INF=1e9+10;
#define readv(x, n) \
vector<int> x(n); \
for (auto &i : x) \
cin >> i;
template <typename t>
using v = vector<t>;
template <typename t>
using vv = vector<vector<t>>;
template <typename t>
using vvv = vector<vector<vector<t>>>;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>> vvvi;
typedef vector<vector<vector<vector<int>>>> vvvvi;
typedef vector<vector<double>> vvd;
typedef pair<int, int> pii;
int multiply(int a, int b, int in_mod) { return (int)(1ll * a * b % in_mod); }
int mult_identity(int a) { return 1; }
const double pi = acosl(-1);
auto power(auto a, auto b, const int in_mod)
{
auto prod = mult_identity(a);
auto mult = a % in_mod;
while (b != 0)
{
if (b % 2)
{
prod = multiply(prod, mult, in_mod);
}
if(b/2)
mult = multiply(mult, mult, in_mod);
b /= 2;
}
return prod;
}
auto mod_inv(auto q, const int in_mod)
{
return power(q, in_mod - 2, in_mod);
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define stp cout << fixed << setprecision(20);
namespace algebra {
using ll = long long;
using uint = unsigned int;
using ull = unsigned long long;
using ld = long double;
template<typename T> using max_heap = std::priority_queue<T>;
template<typename T> using min_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>;
struct modinfo
{
const uint mod, root, max2p;
};
template<const modinfo& info>
class modint
{
public:
static constexpr const uint& mod = 998244353;
static constexpr const uint& root = 3;
static constexpr const uint& max2p = 23;
constexpr modint() : m_val{0} {}
constexpr modint(const ll v) : m_val{normll(v)} {}
constexpr modint(const modint& m) = default;
constexpr void set_raw(const uint v) { m_val = v; }
constexpr modint& operator=(const modint& m) { return m_val = m(), (*this); }
constexpr modint& operator=(const ll v) { return m_val = normll(v), (*this); }
constexpr modint operator+() const { return *this; }
constexpr modint operator-() const { return modint{0} - (*this); }
constexpr modint& operator+=(const modint& m) { return m_val = norm(m_val + m()), *this; }
constexpr modint& operator-=(const modint& m) { return m_val = norm(m_val + mod - m()), *this; }
constexpr modint& operator*=(const modint& m) { return m_val = normll((ll)m_val * (ll)m() % (ll)mod), *this; }
constexpr modint& operator/=(const modint& m) { return *this *= m.inv(); }
constexpr modint& operator+=(const ll val) { return *this += modint{val}; }
constexpr modint& operator-=(const ll val) { return *this -= modint{val}; }
constexpr modint& operator*=(const ll val) { return *this *= modint{val}; }
constexpr modint& operator/=(const ll val) { return *this /= modint{val}; }
constexpr modint operator+(const modint& m) const { return modint{*this} += m; }
constexpr modint operator-(const modint& m) const { return modint{*this} -= m; }
constexpr modint operator*(const modint& m) const { return modint{*this} *= m; }
constexpr modint operator/(const modint& m) const { return modint{*this} /= m; }
constexpr modint operator+(const ll v) const { return *this + modint{v}; }
constexpr modint operator-(const ll v) const { return *this - modint{v}; }
constexpr modint operator*(const ll v) const { return *this * modint{v}; }
constexpr modint operator/(const ll v) const { return *this / modint{v}; }
constexpr bool operator==(const modint& m) const { return m_val == m(); }
constexpr bool operator!=(const modint& m) const { return not(*this == m); }
constexpr friend modint operator+(const ll v, const modint& m) { return modint{v} + m; }
constexpr friend modint operator-(const ll v, const modint& m) { return modint{v} - m; }
constexpr friend modint operator*(const ll v, const modint& m) { return modint{v} * m; }
constexpr friend modint operator/(const ll v, const modint& m) { return modint{v} / m; }
friend std::istream& operator>>(std::istream& is, modint& m)
{
ll v;
return is >> v, m = v, is;
}
friend std::ostream& operator<<(std::ostream& os, const modint& m) { return os << m(); }
constexpr uint operator()() const { return m_val; }
constexpr modint pow(ull n) const
{
modint ans = 1;
for (modint x = *this; n > 0; n >>= 1, x *= x) {
if (n & 1ULL) { ans *= x; }
}
return ans;
}
constexpr modint inv() const { return pow(mod - 2); }
modint sinv() const { return sinv(m_val); }
static modint fact(const uint n)
{
static std::vector<modint> fs{1, 1};
for (uint i = (uint)fs.size(); i <= n; i++) { fs.push_back(fs.back() * i); }
return fs[n];
}
static modint ifact(const uint n)
{
static std::vector<modint> ifs{1, 1};
for (uint i = (uint)ifs.size(); i <= n; i++) { ifs.push_back(ifs.back() * sinv(i)); }
return ifs[n];
}
static modint perm(const int n, const int k) { return k > n or k < 0 ? modint{0} : fact(n) * ifact(n - k); }
static modint comb(const int n, const int k) { return k > n or k < 0 ? modint{0} : fact(n) * ifact(n - k) * ifact(k); }
private:
static constexpr uint norm(const uint x) { return x < mod ? x : x - mod; }
static constexpr uint normll(const ll x) { return norm(uint(x % (ll)mod + (ll)mod)); }
static modint sinv(const uint n)
{
static std::vector<modint> is{1, 1};
for (uint i = (uint)is.size(); i <= n; i++) { is.push_back(-is[mod % i] * (mod / i)); }
return is[n];
}
uint m_val;
};
constexpr modinfo modinfo_1000000007 = {1000000007, 5, 1};
constexpr modinfo modinfo_998244353 = {998244353, 3, 23};
using modint_1000000007 = modint<modinfo_1000000007>;
using modint_998244353 = modint<modinfo_998244353>;
constexpr int popcount(const ull v) { return v ? __builtin_popcountll(v) : 0; }
constexpr int log2p1(const ull v) { return v ? 64 - __builtin_clzll(v) : 0; }
constexpr int lsbp1(const ull v) { return __builtin_ffsll(v); }
constexpr int clog(const ull v) { return v ? log2p1(v - 1) : 0; }
constexpr ull ceil2(const ull v) { return 1ULL << clog(v); }
constexpr ull floor2(const ull v) { return v ? (1ULL << (log2p1(v) - 1)) : 0ULL; }
constexpr bool btest(const ull mask, const int ind) { return (mask >> ind) & 1ULL; }
class range
{
private:
struct itr
{
itr(const int start = 0, const int step = 1) : m_cnt{start}, m_step{step} {}
bool operator!=(const itr& it) const { return m_cnt != it.m_cnt; }
int& operator*() { return m_cnt; }
itr& operator++() { return m_cnt += m_step, *this; }
int m_cnt, m_step;
};
int m_start, m_end, m_step;
public:
range(const int start, const int end, const int step = 1) : m_start{start}, m_end{end}, m_step{step}
{
assert(m_step != 0);
if (m_step > 0) { m_end = m_start + std::max(m_step - 1, m_end - m_start + m_step - 1) / m_step * m_step; }
if (m_step < 0) { m_end = m_start - std::max(-m_step - 1, m_start - m_end - m_step - 1) / (-m_step) * (-m_step); }
}
itr begin() const { return itr{m_start, m_step}; }
itr end() const { return itr{m_end, m_step}; }
};
range rep(const int end, const int step = 1) { return range(0, end, step); }
range per(const int rend, const int step = -1) { return range(rend - 1, -1, step); }
template<typename mint>
class ntt
{
private:
static constexpr const uint& mod = mint::mod;
static constexpr const uint& root = mint::root;
static constexpr const uint& max2p = mint::max2p;
public:
ntt() = delete;
static void trans(std::vector<mint>& as, const int lg, const bool rev)
{
const int N = as.size();
static std::vector<mint> rs;
static std::vector<mint> irs;
if (rs.empty()) {
const mint r = mint(root), ir = r.inv();
rs.resize(max2p + 1), irs.resize(max2p + 1);
rs.back() = -r.pow((mod - 1) >> max2p), irs.back() = -ir.pow((mod - 1) >> max2p);
for (uint i = max2p; i >= 1; i--) { rs[i - 1] = -(rs[i] * rs[i]), irs[i - 1] = -(irs[i] * irs[i]); }
}
const auto rang = (rev ? range(0, lg, 1) : range(lg - 1, -1, -1));
for (const int d : rang) {
const int width = 1 << d;
mint e = 1;
for (int i = 0, j = 1; i < N; i += width * 2, j++) {
for (int l = i, r = i + width; l < i + width; l++, r++) {
const mint x = as[l], y = (rev ? as[r] : as[r] * e);
as[l] = x + y, as[r] = (rev ? (x - y) * e : x - y);
}
e *= (rev ? irs : rs)[lsbp1(j) + 1];
}
}
}
static std::vector<mint> convolute(std::vector<mint> as, std::vector<mint> bs)
{
const int need = as.size() + bs.size() - 1, lg = clog(need), size = 1UL << lg;
as.resize(size), bs.resize(size);
trans(as, lg, false), trans(bs, lg, false);
for (int i = 0; i < size; i++) { as[i] *= bs[i]; }
trans(as, lg, true);
const auto isize = mint{size}.inv();
for (int i = 0; i < need; i++) { as[i] *= isize; }
return std::vector<mint>(as.begin(), as.begin() + need);
}
};
template<typename mint>
class fps
{
private:
static constexpr const uint& mod = mint::mod;
static constexpr const uint& root = mint::root;
static constexpr const uint& max2p = mint::max2p;
// static constexpr modinfo info1 = {469762049, 3, 26};
// static constexpr modinfo info2 = {167772161, 3, 25};
// static constexpr modinfo info3 = {754974721, 11, 24};
// using mint1 = modint<info1>;
// using mint2 = modint<info2>;
// using mint3 = modint<info3>;
// static constexpr mint2 ip1 = mint2{mint1::mod}.inv();
// static constexpr mint3 ip2 = mint3{mint2::mod}.inv();
// static constexpr mint3 ip1p2 = mint3{mint1::mod}.inv() * mint3{mint2::mod}.inv();
// static constexpr mint p1 = mint{mint1::mod};
// static constexpr mint p1p2 = mint{mint1::mod} * mint{mint2::mod};
template<typename submint>
static std::vector<submint> conv(const std::vector<mint>& as, const std::vector<mint>& bs)
{
std::vector<submint> As(as.size()), Bs(bs.size());
for (int i = 0; i < (int)as.size(); i++) { As[i] = as[i](); }
for (int i = 0; i < (int)bs.size(); i++) { Bs[i] = bs[i](); }
return ntt<submint>::convolute(As, Bs);
}
public:
std::vector<mint> convolute(const std::vector<mint>& as, const std::vector<mint>& bs)
{
const int N = as.size() + bs.size() - 1;
if (N <= (1 << max2p)) {
return ntt<mint>::convolute(as, bs);
} else {
}
}
};
const int inf = 1e9;
const int magic = 500; // threshold for sizes to run the naive algo
namespace fft {
const int maxn = 1 << 19;
typedef double ftype;
typedef complex<ftype> point;
vector<point> w;
const ftype pi = acos(-1);
bool initiated = 0;
void init() {
if(!initiated) {
w.resize(maxn);
for(int i = 1; i < maxn; i *= 2) {
for(int j = 0; j < i; j++) {
w[i + j] = polar(ftype(1),2* pi * j / i);
}
}
initiated = 1;
}
}
template<typename T>
void fft(T *in, point *out, int n) {
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(in[i], in[j]);
}
for (int len = 2; len <= n; len <<= 1) {
for (int i = 0; i < n; i += len) {
for (int j = 0; j < len / 2; j++) {
point u = in[i+j], v = in[i+j+len/2] * w[j + len];
in[i+j] = u + v;
in[i+j+len/2] = u - v;
}
}
}
for(int i= 0;i<n;i++)
out[i] = in[i];
}
template<typename T>
void mul_slow(vector<T> &a, const vector<T> &b) {
vector<T> res(a.size() + b.size() - 1);
for(size_t i = 0; i < a.size(); i++) {
for(size_t j = 0; j < b.size(); j++) {
res[i + j] += a[i] * b[j];
}
}
a = res;
}
template<typename T>
void mul(vector<T> &a, const vector<T> &b) {
if(a.size() == 0 && b.size() == 0)
{
a = {};
return;
}
if(min(a.size(), b.size()) < magic) {
mul_slow(a, b);
return;
}
using mint = modint_998244353;
int N = a.size();
int M = b.size();
std::vector<mint> as(N), bs(M);
for(int i = 0;i<N;i++)
as[i].set_raw(a[i]);
for(int i = 0;i<M;i++)
bs[i].set_raw(b[i]);
fps<mint> aaaa;
const auto cs = aaaa.convolute(as, bs);
a.resize(cs.size());
for (int i = 0; i < (int)cs.size(); i++) { a[i] = cs[i](); }
}
}
template<typename T>
T bpow(T x, size_t n) {
return n ? n % 2 ? x * bpow(x, n - 1) : bpow(x * x, n / 2) : T(1);
}
template<typename T>
T bpow(T x, size_t n, T m) {
return n ? n % 2 ? x * bpow(x, n - 1, m) % m : bpow(x * x % m, n / 2, m) : T(1);
}
template<typename T>
T gcd(const T &a, const T &b) {
return b == T(0) ? a : gcd(b, a % b);
}
template<typename T>
T nCr(T n, int r) { // runs in O(r)
T res(1);
for(int i = 0; i < r; i++) {
res *= (n - T(i));
res /= (i + 1);
}
return res;
}
template<int m>
struct modular {
int64_t r;
modular() : r(0) {}
modular(int64_t rr) : r(rr) {if(abs(r) >= m) r %= m; if(r < 0) r += m;}
modular inv() const {return bpow(*this, m - 2);}
modular operator * (const modular &t) const {return (r * t.r) % m;}
modular operator / (const modular &t) const {return *this * t.inv();}
modular operator += (const modular &t) {r += t.r; if(r >= m) r -= m; return *this;}
modular operator -= (const modular &t) {r -= t.r; if(r < 0) r += m; return *this;}
modular operator + (const modular &t) const {return modular(*this) += t;}
modular operator - (const modular &t) const {return modular(*this) -= t;}
modular operator *= (const modular &t) {return *this = *this * t;}
modular operator /= (const modular &t) {return *this = *this / t;}
bool operator == (const modular &t) const {return r == t.r;}
bool operator != (const modular &t) const {return r != t.r;}
operator int64_t() const {return r;}
};
template<int T>
istream& operator >> (istream &in, modular<T> &x) {
return in >> x.r;
}
template<typename T>
struct poly {
vector<T> a;
void normalize() { // get rid of leading zeroes
while(!a.empty() && a.back() == T(0)) {
a.pop_back();
}
}
poly(){}
poly(T a0) : a{a0}{normalize();}
poly(vector<T> t) : a(t){normalize();}
poly operator += (const poly &t) {
a.resize(max(a.size(), t.a.size()));
for(size_t i = 0; i < t.a.size(); i++) {
a[i] += t.a[i];
}
normalize();
return *this;
}
poly operator -= (const poly &t) {
a.resize(max(a.size(), t.a.size()));
for(size_t i = 0; i < t.a.size(); i++) {
a[i] -= t.a[i];
}
normalize();
return *this;
}
poly operator + (const poly &t) const {return poly(*this) += t;}
poly operator - (const poly &t) const {return poly(*this) -= t;}
poly mod_xk(size_t k) const { // get same polynomial mod x^k
k = min(k, a.size());
return vector<T>(begin(a), begin(a) + k);
}
poly mul_xk(size_t k) const { // multiply by x^k
poly res(*this);
res.a.insert(begin(res.a), k, 0);
return res;
}
poly div_xk(size_t k) const { // divide by x^k, dropping coefficients
k = min(k, a.size());
return vector<T>(begin(a) + k, end(a));
}
poly substr(size_t l, size_t r) const { // return mod_xk(r).div_xk(l)
l = min(l, a.size());
r = min(r, a.size());
return vector<T>(begin(a) + l, begin(a) + r);
}
poly inv(size_t n) const { // get inverse series mod x^n
assert(!is_zero());
poly ans = a[0].inv();
size_t a = 1;
while(a < n) {
poly C = (ans * mod_xk(2 * a)).substr(a, 2 * a);
ans -= (ans * C).mod_xk(a).mul_xk(a);
a *= 2;
}
return ans.mod_xk(n);
}
poly operator *= (const poly &t) {fft::mul(a, t.a); normalize(); return *this;}
poly operator * (const poly &t) const {return poly(*this) *= t;}
poly reverse(size_t n, bool rev = 0) const { // reverses and leaves only n terms
poly res(*this);
if(rev) { // If rev = 1 then tail goes to head
res.a.resize(max(n, res.a.size()));
}
std::reverse(res.a.begin(), res.a.end());
return res.mod_xk(n);
}
pair<poly, poly> divmod_slow(const poly &b) const { // when divisor or quotient is small
vector<T> A(a);
vector<T> res;
while(A.size() >= b.a.size()) {
res.push_back(A.back() / b.a.back());
if(res.back() != T(0)) {
for(size_t i = 0; i < b.a.size(); i++) {
A[A.size() - i - 1] -= res.back() * b.a[b.a.size() - i - 1];
}
}
A.pop_back();
}
std::reverse(begin(res), end(res));
return {res, A};
}
pair<poly, poly> divmod(const poly &b) const { // returns quotiend and remainder of a mod b
if(deg() < b.deg()) {
return {poly{0}, *this};
}
int d = deg() - b.deg();
if(min(d, b.deg()) < magic) {
return divmod_slow(b);
}
poly D = (reverse(d + 1) * b.reverse(d + 1).inv(d + 1)).mod_xk(d + 1).reverse(d + 1, 1);
return {D, *this - D * b};
}
poly operator / (const poly &t) const {return divmod(t).first;}
poly operator % (const poly &t) const {return divmod(t).second;}
poly operator /= (const poly &t) {return *this = divmod(t).first;}
poly operator %= (const poly &t) {return *this = divmod(t).second;}
poly operator *= (const T &x) {
for(auto &it: a) {
it *= x;
}
normalize();
return *this;
}
poly operator /= (const T &x) {
for(auto &it: a) {
it /= x;
}
normalize();
return *this;
}
poly operator * (const T &x) const {return poly(*this) *= x;}
poly operator / (const T &x) const {return poly(*this) /= x;}
void print() const {
for(auto it: a) {
cout << it << ' ';
}
cout << endl;
}
T eval(T x) const { // evaluates in single point x
T res(0);
for(int i = int(a.size()) - 1; i >= 0; i--) {
res *= x;
res += a[i];
}
return res;
}
T& lead() { // leading coefficient
return a.back();
}
int deg() const { // degree
return a.empty() ? -inf : a.size() - 1;
}
bool is_zero() const { // is polynomial zero
return a.empty();
}
T operator [](int idx) const {
return idx >= (int)a.size() || idx < 0 ? T(0) : a[idx];
}
T& coef(size_t idx) { // mutable reference at coefficient
return a[idx];
}
bool operator == (const poly &t) const {return a == t.a;}
bool operator != (const poly &t) const {return a != t.a;}
poly deriv() { // calculate derivative
vector<T> res;
for(int i = 1; i <= deg(); i++) {
res.push_back(T(i) * a[i]);
}
return res;
}
poly integr() { // calculate integral with C = 0
vector<T> res = {0};
for(int i = 0; i <= deg(); i++) {
res.push_back(a[i] / T(i + 1));
}
return res;
}
size_t leading_xk() const { // Let p(x) = x^k * t(x), return k
if(is_zero()) {
return inf;
}
int res = 0;
while(a[res] == T(0)) {
res++;
}
return res;
}
poly log(size_t n) { // calculate log p(x) mod x^n
assert(a[0] == T(1));
return (deriv().mod_xk(n) * inv(n)).integr().mod_xk(n);
}
poly exp(size_t n) { // calculate exp p(x) mod x^n
if(is_zero()) {
return T(1);
}
assert(a[0] == T(0));
poly ans = T(1);
size_t a = 1;
while(a < n) {
poly C = ans.log(2 * a).div_xk(a) - substr(a, 2 * a);
ans -= (ans * C).mod_xk(a).mul_xk(a);
a *= 2;
}
return ans.mod_xk(n);
}
poly pow_slow(size_t k, size_t n) { // if k is small
return k ? k % 2 ? (*this * pow_slow(k - 1, n)).mod_xk(n) : (*this * *this).mod_xk(n).pow_slow(k / 2, n) : T(1);
}
poly pow(size_t k, size_t n) { // calculate p^k(n) mod x^n
if(k == 0)
{
return {1};
}
if(is_zero()) {
return *this;
}
if(k < magic) {
return pow_slow(k, n);
}
int i = leading_xk();
T j = a[i];
poly t = div_xk(i) / j;
return bpow(j, k) * (t.log(n) * T(k)).exp(n).mul_xk(i * k).mod_xk(n);
}
poly mulx(T x) { // component-wise multiplication with x^k
T cur = 1;
poly res(*this);
for(int i = 0; i <= deg(); i++) {
res.coef(i) *= cur;
cur *= x;
}
return res;
}
poly mulx_sq(T x) { // component-wise multiplication with x^{k^2}
T cur = x;
T total = 1;
T xx = x * x;
poly res(*this);
for(int i = 0; i <= deg(); i++) {
res.coef(i) *= total;
total *= cur;
cur *= xx;
}
return res;
}
vector<T> chirpz_even(T z, int n) { // P(1), P(z^2), P(z^4), ..., P(z^2(n-1))
int m = deg();
if(is_zero()) {
return vector<T>(n, 0);
}
vector<T> vv(m + n);
T zi = z.inv();
T zz = zi * zi;
T cur = zi;
T total = 1;
for(int i = 0; i <= max(n - 1, m); i++) {
if(i <= m) {vv[m - i] = total;}
if(i < n) {vv[m + i] = total;}
total *= cur;
cur *= zz;
}
poly w = (mulx_sq(z) * vv).substr(m, m + n).mulx_sq(z);
vector<T> res(n);
for(int i = 0; i < n; i++) {
res[i] = w[i];
}
return res;
}
vector<T> chirpz(T z, int n) { // P(1), P(z), P(z^2), ..., P(z^(n-1))
auto even = chirpz_even(z, (n + 1) / 2);
auto odd = mulx(z).chirpz_even(z, n / 2);
vector<T> ans(n);
for(int i = 0; i < n / 2; i++) {
ans[2 * i] = even[i];
ans[2 * i + 1] = odd[i];
}
if(n % 2 == 1) {
ans[n - 1] = even.back();
}
return ans;
}
template<typename iter>
vector<T> eval(vector<poly> &tree, int v, iter l, iter r) { // auxiliary evaluation function
if(r - l == 1) {
return {eval(*l)};
} else {
auto m = l + (r - l) / 2;
auto A = (*this % tree[2 * v]).eval(tree, 2 * v, l, m);
auto B = (*this % tree[2 * v + 1]).eval(tree, 2 * v + 1, m, r);
A.insert(end(A), begin(B), end(B));
return A;
}
}
vector<T> eval(vector<T> x) { // evaluate polynomial in (x1, ..., xn)
int n = x.size();
if(is_zero()) {
return vector<T>(n, T(0));
}
vector<poly> tree(4 * n);
build(tree, 1, begin(x), end(x));
return eval(tree, 1, begin(x), end(x));
}
template<typename iter>
poly inter(vector<poly> &tree, int v, iter l, iter r, iter ly, iter ry) { // auxiliary interpolation function
if(r - l == 1) {
return {*ly / a[0]};
} else {
auto m = l + (r - l) / 2;
auto my = ly + (ry - ly) / 2;
auto A = (*this % tree[2 * v]).inter(tree, 2 * v, l, m, ly, my);
auto B = (*this % tree[2 * v + 1]).inter(tree, 2 * v + 1, m, r, my, ry);
return A * tree[2 * v + 1] + B * tree[2 * v];
}
}
};
template<typename T>
poly<T> operator * (const T& a, const poly<T>& b) {
return b * a;
}
template<typename T>
poly<T> xk(int k) { // return x^k
return poly<T>{1}.mul_xk(k);
}
template<typename T>
T resultant(poly<T> a, poly<T> b) { // computes resultant of a and b
if(b.is_zero()) {
return 0;
} else if(b.deg() == 0) {
return bpow(b.lead(), a.deg());
} else {
int pw = a.deg();
a %= b;
pw -= a.deg();
T mul = bpow(b.lead(), pw) * T((b.deg() & a.deg() & 1) ? -1 : 1);
T ans = resultant(b, a);
return ans * mul;
}
}
template<typename iter>
poly<typename iter::value_type> kmul(iter L, iter R) { // computes (x-a1)(x-a2)...(x-an) without building tree
if(R - L == 1) {
return vector<typename iter::value_type>{-*L, 1};
} else {
iter M = L + (R - L) / 2;
return kmul(L, M) * kmul(M, R);
}
}
template<typename T, typename iter>
poly<T> build(vector<poly<T>> &res, int v, iter L, iter R) { // builds evaluation tree for (x-a1)(x-a2)...(x-an)
if(R - L == 1) {
return res[v] = vector<T>{-*L, 1};
} else {
iter M = L + (R - L) / 2;
return res[v] = build(res, 2 * v, L, M) * build(res, 2 * v + 1, M, R);
}
}
template<typename T>
poly<T> inter(vector<T> x, vector<T> y) { // interpolates minimum polynomial from (xi, yi) pairs
int n = x.size();
vector<poly<T>> tree(4 * n);
return build(tree, 1, begin(x), end(x)).deriv().inter(tree, 1, begin(x), end(x), begin(y), end(y));
}
};
using namespace algebra;
typedef modular<mod> base;
typedef poly<base> polyn;
using namespace algebra;
const int MAXN=2e5+10;
vector<base> fac(MAXN);
vector<base> infac(MAXN);
void build_factorial()
{
fac[0]=1;
infac[0]=1;
for(int i=1;i<MAXN;i++)
{
fac[i]=(fac[i-1]*(base)i);
}
infac[MAXN-1] = power(fac[MAXN -1], mod - 2,mod);
for(int i= MAXN-2;i>=0;i--)
{
infac[i] = infac[i+1] *base(i + 1);
}
}
base ncr(int n, int r)
{
if(n<r)
return 0;
return fac[n] * infac[r] * infac[n-r];
}
void solv()
{
build_factorial();
int k, q;
cin>>k>>q;
const int maxn = 1e5 + 10;
polyn x;
x.a.resize(maxn + 1);
for(int i = 0 ;i<=maxn;i+=2)
x.a[i] = ncr(i, i/2) * ncr(i,i/2);
polyn power_4;
power_4.a.resize(maxn + 1);
power_4.a[0] = 1;
for(int i = 1 ;i<=maxn;i++)
power_4.a[i] = power_4.a[i-1] * base(4);
polyn Q;
auto l = x.inv(maxn + 1);
Q = power_4 * l;
Q = Q.mod_xk(maxn + 1);
polyn P(1);
P = P - l;
P = P.mod_xk(maxn + 1);
if(k == 1)
{
polyn A = Q.deriv() *polyn({0,1});
polyn E = A * power_4;
while(q--)
{
int n , p;
cin>>n>>p;
base ans = (E )[n]/ base(power(4,n, mod));
cout<<ans<<endl;
}
}
else
{
polyn D;
D.a.resize(maxn/2 + 1);
for(int i = 0;i<=maxn/2;i++)
D.a[i] = P[2*i];
D = D.pow(k-2,maxn/2 +1);
polyn Z;
Z.a.resize(maxn + 1);
for(int i = 0;i<=maxn/2;i++)
Z.a[2*i] = D[i];
polyn left = ((Q.deriv() *Z).mod_xk(maxn+1) * P).mul_xk(1).mod_xk(maxn+1) ;
polyn right = ((Q *Z).mod_xk(maxn+1) * P.deriv() ).mul_xk(1).mod_xk(maxn+1);
left *= power_4;
right *= power_4;
left = left.mod_xk(maxn+1);
right = right.mod_xk(maxn+1);
while(q--)
{
int n, p;
cin>>n>>p;
base ans =(left[n] + base(p-1) * right[n]) *base(mod_inv(power(4, n , mod), mod));
cout<<ans<<endl;
}
}
}
void solve()
{
int t = 1;
// cin>>t;
while(t--)
{
solv();
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cerr.tie(NULL);
auto clk = clock();
// -------------------------------------Code starts here---------------------------------------------------------------------
signed t = 1;
// cin >> t;
for (signed test = 1; test <= t; test++)
{
// cout<<"Case #"<<test<<": ";
// cout<<endl;
solve();
}
// -------------------------------------Code ends here------------------------------------------------------------------
clk = clock() - clk;
#ifndef ONLINE_JUDGE
// cerr << fixed << setprecision(6) << "\nTime: " << ((float)clk) / CLOCKS_PER_SEC << "\n";
#endif
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer, print whether that integer is a prime number or not.First line of input contains an integer T, showing the number of test cases. Every test case is a single integer A.
Constraints
1 <= T <= 100
1 <= A <= 10^8If the given integer is prime, print 'Yes', else print 'No'.Sample Input
3
5
9
13
Output
Yes
No
Yes, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcase = Integer.parseInt(br.readLine());
for(int t=0;t<testcase;t++){
int num = Integer.parseInt(br.readLine().trim());
if(num==1)
System.out.println("No");
else if(num<=3)
System.out.println("Yes");
else{
if((num%2==0)||(num%3==0))
System.out.println("No");
else{
int flag=0;
for(int i=5;i*i<=num;i+=6){
if(((num%i)==0)||(num%(i+2)==0)){
System.out.println("No");
flag=1;
break;
}
}
if(flag==0)
System.out.println("Yes");
}
}
}
}catch (Exception e) {
System.out.println("I caught: " + e);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer, print whether that integer is a prime number or not.First line of input contains an integer T, showing the number of test cases. Every test case is a single integer A.
Constraints
1 <= T <= 100
1 <= A <= 10^8If the given integer is prime, print 'Yes', else print 'No'.Sample Input
3
5
9
13
Output
Yes
No
Yes, I have written this Solution Code: t=int(input())
for i in range(t):
number = int(input())
if number > 1:
i=2
while i*i<=number:
if (number % i) == 0:
print("No")
break
i+=1
else:
print("Yes")
else:
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer, print whether that integer is a prime number or not.First line of input contains an integer T, showing the number of test cases. Every test case is a single integer A.
Constraints
1 <= T <= 100
1 <= A <= 10^8If the given integer is prime, print 'Yes', else print 'No'.Sample Input
3
5
9
13
Output
Yes
No
Yes, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
long long n,k;
cin>>n;
long x=sqrt(n);
int cnt=0;
vector<int> v;
for(long long i=2;i<=x;i++){
if(n%i==0){
cout<<"No"<<endl;
goto f;
}}
cout<<"Yes"<<endl;
f:;
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Phoebe is a big GCD fan. Being bored, she starts counting number of pairs of integers (A, B) such that following conditions are satisfied:
<li> GCD(A, B) = X (As X is Phoebe's favourite integer)
<li> A <= B <= L
As Phoebe's performance is coming up, she needs your help to find the number of such pairs possible.
Note: GCD refers to the <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">Greatest common divisor</a>.Input contains two integers L and X.
Constraints:
1 <= L, X <= 1000000000Print a single integer denoting number of pairs possible.Sample Input
5 2
Sample Output
2
Explanation: Pairs satisfying all conditions are: (2, 2), (2, 4)
Sample Input
5 3
Sample Output
1
Explanation: Pairs satisfying all conditions are: (3, 3), I have written this Solution Code: import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
out.println(sumTotient(ni()/ni()));
}
public static int[] enumTotientByLpf(int n, int[] lpf)
{
int[] ret = new int[n+1];
ret[1] = 1;
for(int i = 2;i <= n;i++){
int j = i/lpf[i];
if(lpf[j] != lpf[i]){
ret[i] = ret[j] * (lpf[i]-1);
}else{
ret[i] = ret[j] * lpf[i];
}
}
return ret;
}
public static int[] enumLowestPrimeFactors(int n)
{
int tot = 0;
int[] lpf = new int[n+1];
int u = n+32;
double lu = Math.log(u);
int[] primes = new int[(int)(u/lu+u/lu/lu*1.5)];
for(int i = 2;i <= n;i++)lpf[i] = i;
for(int p = 2;p <= n;p++){
if(lpf[p] == p)primes[tot++] = p;
int tmp;
for(int i = 0;i < tot && primes[i] <= lpf[p] && (tmp = primes[i]*p) <= n;i++){
lpf[tmp] = primes[i];
}
}
return lpf;
}
public static long sumTotient(int n)
{
if(n == 0)return 0L;
if(n == 1)return 1L;
int s = (int)Math.sqrt(n);
long[] cacheu = new long[n/s];
long[] cachel = new long[s+1];
int X = (int)Math.pow(n, 0.66);
int[] lpf = enumLowestPrimeFactors(X);
int[] tot = enumTotientByLpf(X, lpf);
long sum = 0;
int p = cacheu.length-1;
for(int i = 1;i <= X;i++){
sum += tot[i];
if(i <= s){
cachel[i] = sum;
}else if(p > 0 && i == n/p){
cacheu[p] = sum;
p--;
}
}
for(int i = p;i >= 1;i--){
int x = n/i;
long all = (long)x*(x+1)/2;
int ls = (int)Math.sqrt(x);
for(int j = 2;x/j > ls;j++){
long lval = i*j < cacheu.length ? cacheu[i*j] : cachel[x/j];
all -= lval;
}
for(int v = ls;v >= 1;v--){
long w = x/v-x/(v+1);
all -= cachel[v]*w;
}
cacheu[(int)i] = all;
}
return cacheu[1];
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Phoebe is a big GCD fan. Being bored, she starts counting number of pairs of integers (A, B) such that following conditions are satisfied:
<li> GCD(A, B) = X (As X is Phoebe's favourite integer)
<li> A <= B <= L
As Phoebe's performance is coming up, she needs your help to find the number of such pairs possible.
Note: GCD refers to the <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">Greatest common divisor</a>.Input contains two integers L and X.
Constraints:
1 <= L, X <= 1000000000Print a single integer denoting number of pairs possible.Sample Input
5 2
Sample Output
2
Explanation: Pairs satisfying all conditions are: (2, 2), (2, 4)
Sample Input
5 3
Sample Output
1
Explanation: Pairs satisfying all conditions are: (3, 3), I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
template<class C> void mini(C&a4, C b4){a4=min(a4,b4);}
typedef unsigned long long ull;
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define mod 1000000007ll
#define pii pair<int,int>
/////////////
ull X[20000001];
ull cmp(ull N){
return N*(N+1)/2;
}
ull solve(ull N){
if(N==1)
return 1;
if(N < 20000001 && X[N] != 0)
return X[N];
ull res = 0;
ull q = floor(sqrt(N));
for(int k=2;k<N/q+1;++k){
res += solve(N/k);
}
for(int m=1;m<q;++m){
res += (N/m - N/(m+1)) * solve(m);
}
res = cmp(N) - res;
if(N < 20000001)
X[N] = res;
return res;
}
signed main(){
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int l,x;
cin>>l>>x;
if(l<x)
cout<<0;
else
cout<<solve(l/x);
#ifdef ANIKET_GOYAL
cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N and F(N) find value of F(1), if, F(i)=(F(i-1) + F(i-1))%1000000007 and 0 <= F(1) < 1000000007.First and the only line of input contains two integers N and F(N).
Constraints:
1 <= N <= 1000000000
0 <= F(N) < 1000000007Print a single integer, F(1).Sample Input 1
2 6
Sample Output 1
3
Exlpanation: F(1) = 3, F(2)=(3+3)%1000000007 = 6.
Sample Input 2
3 6
Sample Input 2
500000005
Explanation:
F(1) = 500000005
F(2) = (500000005+500000005)%1000000007 = 3
F(3)= (3+3)%1000000007 = 6, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
int n=Integer.parseInt(st.nextToken());
int fn=Integer.parseInt(st.nextToken());
long ans=fn;
int P=1000000007;
long inv2n=(long)pow(pow(2,n-1,P)%P,P-2,P);
ans=((ans%P)*(inv2n%P))%P;
System.out.println((ans)%P);
}
static long pow(long x, long y,long P)
{
long res = 1l;
while (y > 0)
{
if ((y & 1) == 1)
res = (res * x)%P;
y = y >> 1;
x = (x * x)%P;
}
return res;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N and F(N) find value of F(1), if, F(i)=(F(i-1) + F(i-1))%1000000007 and 0 <= F(1) < 1000000007.First and the only line of input contains two integers N and F(N).
Constraints:
1 <= N <= 1000000000
0 <= F(N) < 1000000007Print a single integer, F(1).Sample Input 1
2 6
Sample Output 1
3
Exlpanation: F(1) = 3, F(2)=(3+3)%1000000007 = 6.
Sample Input 2
3 6
Sample Input 2
500000005
Explanation:
F(1) = 500000005
F(2) = (500000005+500000005)%1000000007 = 3
F(3)= (3+3)%1000000007 = 6, I have written this Solution Code: n,f=map(int,input().strip().split())
mod=10**9+7
m1=pow(2,n-1,mod)
m=pow(m1,mod-2,mod)
print(f*m%mod), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N and F(N) find value of F(1), if, F(i)=(F(i-1) + F(i-1))%1000000007 and 0 <= F(1) < 1000000007.First and the only line of input contains two integers N and F(N).
Constraints:
1 <= N <= 1000000000
0 <= F(N) < 1000000007Print a single integer, F(1).Sample Input 1
2 6
Sample Output 1
3
Exlpanation: F(1) = 3, F(2)=(3+3)%1000000007 = 6.
Sample Input 2
3 6
Sample Input 2
500000005
Explanation:
F(1) = 500000005
F(2) = (500000005+500000005)%1000000007 = 3
F(3)= (3+3)%1000000007 = 6, I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
long long powerm(long long x, unsigned long long y, long long p)
{
long long res = 1;
x = x % p;
while (y > 0)
{
if (y & 1)
res = (res*x) % p;
y = y>>1;
x = (x*x) % p;
}
return res;
}
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n,fn;
cin>>n>>fn;
int mo=1000000007;
cout<<(fn*powerm(powerm(2,n-1,mo),mo-2,mo))%mo;
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an unsorted array A[] of integers and size N, and an element X, you need to find the Minimum Number of Elements required to be added to this array so the new median of array becomes X.
Median of array is middle element of array in its sorted form. For odd number of elements N it is the element at position (N-1)/2. For even number of elements N, it is (A[N/2] + A[(N/2) - 1])/2.
Try without sorting the arrayThe first line contains number of testcases T. Every testcase consists of 2 lines, first line contains N - no of element of arrays and X, and second line contains Array elements in unsorted manner.
Constraints:
1 <= T <= 100
1 <= N <= 2*10^5
1 <= X <= 10^6
1 <= A[i] <= 10^6
Sum of N for every test case is less than or equal to 2*10^5You need to find total number of elements to be added to array so that the new median becomes equal to X.Sample Input:
2
6 30
10 20 30 100 150 200
5 50
10 20 30 100 150
Sample Output:
1
1
Explanation:
Testcase 1: Only 1 element before 30 is required to be added to the array, to make median of array 30.
Testcase 2: Only 1 element between 30 and 100, i. e number 70 is required to be added to make median 50., I have written this Solution Code: for i in range(int(input())):
n,k=map(int,input().split())
x=list(map(int,input().split()))
count,large_count,small_count,small,large=0,0,0,-1,10000000
for i in x:
if i==k:
count+=1
if i>k:
large_count+=1
large=min(large,i)
if i<k:
small_count+=1
small=max(small,i)
ans=abs(large_count-small_count)
if(count>0):
if(count>=n/2):
print(0)
else:
print(ans)
elif(small_count==large_count):
if((large+small)//2==k):
print(0)
else:
print(1)
elif(small_count==0 or large_count==0):
print(n)
else:
t=2*k-small
if(t==large):
print(ans)
elif(t<large):
large_count+=1
print(min(ans+1,abs(large_count-small_count)+1))
elif(t>large):
l=2*k-large
if(l>small):
small_count+=1
print(min(ans+1,abs(large_count-small_count)+1))
else:
print(ans+1), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an unsorted array A[] of integers and size N, and an element X, you need to find the Minimum Number of Elements required to be added to this array so the new median of array becomes X.
Median of array is middle element of array in its sorted form. For odd number of elements N it is the element at position (N-1)/2. For even number of elements N, it is (A[N/2] + A[(N/2) - 1])/2.
Try without sorting the arrayThe first line contains number of testcases T. Every testcase consists of 2 lines, first line contains N - no of element of arrays and X, and second line contains Array elements in unsorted manner.
Constraints:
1 <= T <= 100
1 <= N <= 2*10^5
1 <= X <= 10^6
1 <= A[i] <= 10^6
Sum of N for every test case is less than or equal to 2*10^5You need to find total number of elements to be added to array so that the new median becomes equal to X.Sample Input:
2
6 30
10 20 30 100 150 200
5 50
10 20 30 100 150
Sample Output:
1
1
Explanation:
Testcase 1: Only 1 element before 30 is required to be added to the array, to make median of array 30.
Testcase 2: Only 1 element between 30 and 100, i. e number 70 is required to be added to make median 50., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
signed main() {
IOS;
int t; cin >> t;
while(t--){
int n, x;
cin >> n >> x;
int a = 0, b = 0, c = 0;
int l = 0, r = inf;
for(int i = 1; i <= n; i++){
int p; cin >> p;
if(p < x) a++, l = max(l, p);
else if(p == x) b++;
else c++, r = min(r, p);
}
//cout << l << " " << r << endl;
//cout << a << " " << b << " " << c << endl;
int ans;
if(n&1){
if(a <= n/2){
if(a+b > n/2)
ans = 0;
else{
if(2*x - r >= l && b == 0)
ans = 2*c - n;
else
ans = 2*c + 1 - n;
}
}
else{
if(2*x - l <= r && b == 0)
ans = 2*a - n;
else
ans = 2*a + 1 - n;
}
}
else{
if(a < n/2){
if(c == n)
ans = n;
else if(a+b > n/2)
ans = 0;
else{
if(2*x - r >= l && b == 0)
ans = 2*c - n;
else
ans = 2*c + 1 - n;
}
}
else if(a > n/2){
if(2*x - l <= r && b == 0)
ans = 2*a - n;
else
ans = 2*a + 1 - n;
}
else
ans = 1 - ((l+r) == 2*x);
}
cout << ans << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number n find the number of prime numbers less than equal to that number.There is only one integer containing value of n.
Constraints:-
1 <= n <= 10000000Return number of primes less than or equal to nSample Input
5
Sample Output
3
Explanation:-
2 3 and 5 are the required primes.
Sample Input
5000
Sample Output
669, I have written this Solution Code: #include <bits/stdc++.h>
// #define ll long long
using namespace std;
#define ma 10000001
bool a[ma];
int main()
{
int n;
cin>>n;
for(int i=0;i<=n;i++){
a[i]=false;
}
for(int i=2;i<=n;i++){
if(a[i]==false){
for(int j=i+i;j<=n;j+=i){
a[j]=true;
}
}
}
int cnt=0;
for(int i=2;i<=n;i++){
if(a[i]==false){cnt++;}
}
cout<<cnt;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number n find the number of prime numbers less than equal to that number.There is only one integer containing value of n.
Constraints:-
1 <= n <= 10000000Return number of primes less than or equal to nSample Input
5
Sample Output
3
Explanation:-
2 3 and 5 are the required primes.
Sample Input
5000
Sample Output
669, I have written this Solution Code: import java.io.*;
import java.util.*;
import java.lang.Math;
class Main {
public static void main (String[] args)
throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long n = Integer.parseInt(br.readLine());
long i=2,j,count,noOfPrime=0;
if(n<=1)
System.out.println("0");
else{
while(i<=n)
{
count=0;
for(j=2; j<=Math.sqrt(i); j++)
{
if( i%j == 0 ){
count++;
break;
}
}
if(count==0){
noOfPrime++;
}
i++;
}
System.out.println(noOfPrime);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number n find the number of prime numbers less than equal to that number.There is only one integer containing value of n.
Constraints:-
1 <= n <= 10000000Return number of primes less than or equal to nSample Input
5
Sample Output
3
Explanation:-
2 3 and 5 are the required primes.
Sample Input
5000
Sample Output
669, I have written this Solution Code: function numberOfPrimes(N)
{
let arr = new Array(N+1);
for(let i = 0; i <= N; i++)
arr[i] = 0;
for(let i=2; i<= N/2; i++)
{
if(arr[i] === -1)
{
continue;
}
let p = i;
for(let j=2; p*j<= N; j++)
{
arr[p*j] = -1;
}
}
//console.log(arr);
let count = 0;
for(let i=2; i<= N; i++)
{
if(arr[i] === 0)
{
count++;
}
}
//console.log(arr);
return count;
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number n find the number of prime numbers less than equal to that number.There is only one integer containing value of n.
Constraints:-
1 <= n <= 10000000Return number of primes less than or equal to nSample Input
5
Sample Output
3
Explanation:-
2 3 and 5 are the required primes.
Sample Input
5000
Sample Output
669, I have written this Solution Code: import math
n = int(input())
n=n+1
if n<3:
print(0)
else:
primes=[1]*(n//2)
for i in range(3,int(math.sqrt(n))+1,2):
if primes[i//2]:primes[i*i//2::i]=[0]*((n-i*i-1)//(2*i)+1)
print(sum(primes)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string s, recursively remove adjacent duplicate characters from the string s. The output string should not have any adjacent duplicates. For better understanding see sample.
Note:- Solve this problem while going through left to right.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>remove()</b> that takes the string as parameter.
Constraints:
1<=T<=100
1<=Length of string<=50Return the modified string.
Sample Input:-
3
geeksforgeek
acaaabbbacdddd
abcddcba
Sample Output:-
gksforgk
acac
Explanation:-
for second test case:-
acaaabbbacdddd -> acbbbacdddd -> acacdddd -> acac
for test case 3:-
abcddcba -> abccba -> abba -> aa -> (empty string), I have written this Solution Code: static String remove(String s)
{
Stack<Character> st = new Stack<Character>();
Character prev = 'A';
for(int i=0;i<s.length();i++){
if(st.empty()==true){
if(prev!=s.charAt(i)){
st.push(s.charAt(i));
prev=s.charAt(i);
}}
else{
if(st.peek()==s.charAt(i)){
prev=st.peek();
st.pop();
}
if(prev==s.charAt(i)){continue;}
else{
st.push(s.charAt(i));
prev=st.peek();
}
}
}
String ans="";
while(st.empty()==false){
ans+=st.pop();
}
String res="";
for(int i=ans.length()-1;i>=0;i--){
res+=ans.charAt(i);
}
return res;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: When learning a new language, we first learn to output some messages. Here, we will start with the famous <b>"Hello World"</b> message. Now, here you are given a function to complete. <i>Don't worry about the ins and outs of functions, <b>just add the printing command to print "Hello World", </b></i>.your task is to just print "Hello World", without the quotes.Hello WorldHello World must be printed., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
System.out.print("Hello World");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: When learning a new language, we first learn to output some messages. Here, we will start with the famous <b>"Hello World"</b> message. Now, here you are given a function to complete. <i>Don't worry about the ins and outs of functions, <b>just add the printing command to print "Hello World", </b></i>.your task is to just print "Hello World", without the quotes.Hello WorldHello World must be printed., I have written this Solution Code: def print_fun():
print ("Hello World")
def main():
print_fun()
if __name__ == '__main__':
main(), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer n , your task is to print the lowercase English word corresponding to the number if it is <=5 else print "Greater than 5".
Numbers <=5 and their corresponding words :
1 = one
2 = two
3 = three
4 = four
5 = fiveThe input contains a single integer N.
Constraint:
1 <= n <= 100Print a string consisting of the lowercase English word corresponding to the number if it is <=5 else print the string "Greater than 5"Sample Input:
4
Sample Output
four
Sample Input:
6
Sample Output:
Greater than 5, I have written this Solution Code: N = int(input())
if N > 5:
print("Greater than 5")
elif(N == 1):
print("one")
elif(N == 2):
print("two")
elif(N == 3):
print("three")
elif(N == 4):
print("four")
elif(N == 5):
print("five"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer n , your task is to print the lowercase English word corresponding to the number if it is <=5 else print "Greater than 5".
Numbers <=5 and their corresponding words :
1 = one
2 = two
3 = three
4 = four
5 = fiveThe input contains a single integer N.
Constraint:
1 <= n <= 100Print a string consisting of the lowercase English word corresponding to the number if it is <=5 else print the string "Greater than 5"Sample Input:
4
Sample Output
four
Sample Input:
6
Sample Output:
Greater than 5, I have written this Solution Code: import java.util.Scanner;
class Main {
public static void main (String[] args)
{
//Capture the user's input
Scanner scanner = new Scanner(System.in);
//Storing the captured value in a variable
int side = scanner.nextInt();
String area = conditional(side);
System.out.println(area);
}static String conditional(int n){
if(n==1){return "one";}
else if(n==2){return "two";}
else if(n==3){return "three";}
else if(n==4){return "four";}
else if(n==5){return "five";}
else{
return "Greater than 5";}
}}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an 8*8 empty chessboard in which a rook is placed at a position (X, Y). Your task is to find the minimum steps Rook will take to go to the position (1, 1).The input contains two integer X and Y.
Constraints:-
1 <= X <= 8
1 <= Y <= 8Print the number of steps rook will take to go to the position (X, Y).Sample Input:-
2 4
Sample Output:-
2
Explanation:-
one of the possible paths is:-
(2, 4) - > (2, 1) - > (1, 1)
Sample Input:-
1 2
Sample Output:-
1, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int X = scan.nextInt();
int Y = scan.nextInt();
if((X == 1) && (Y == 1)){
System.out.println(0);
}
else if((X == 1) || (Y == 1)){
System.out.println(1);
}
else{
System.out.println(2);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an 8*8 empty chessboard in which a rook is placed at a position (X, Y). Your task is to find the minimum steps Rook will take to go to the position (1, 1).The input contains two integer X and Y.
Constraints:-
1 <= X <= 8
1 <= Y <= 8Print the number of steps rook will take to go to the position (X, Y).Sample Input:-
2 4
Sample Output:-
2
Explanation:-
one of the possible paths is:-
(2, 4) - > (2, 1) - > (1, 1)
Sample Input:-
1 2
Sample Output:-
1, I have written this Solution Code: X, Y = [int(x) for x in input().split()]
if X == 1 and Y == 1:
print(0)
elif X == 1 or Y == 1:
print(1)
else:
print(2), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an 8*8 empty chessboard in which a rook is placed at a position (X, Y). Your task is to find the minimum steps Rook will take to go to the position (1, 1).The input contains two integer X and Y.
Constraints:-
1 <= X <= 8
1 <= Y <= 8Print the number of steps rook will take to go to the position (X, Y).Sample Input:-
2 4
Sample Output:-
2
Explanation:-
one of the possible paths is:-
(2, 4) - > (2, 1) - > (1, 1)
Sample Input:-
1 2
Sample Output:-
1, I have written this Solution Code: #include <iostream>
using namespace std;
int Rook(int X, int Y){
//Enter your code here
if(X==1 && Y==1){return 0;}
if(X==1 || Y==1){return 1;}
return 2;
}
int main(){
int x,y;
scanf("%d%d",&x,&y);
printf("%d",Rook(x,y));
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, print all balanced bracket strings of length 2*N.
A bracket string is a string that contains only '(' and ')' as its characters.
<ul>
<li>Empty string is a balanced bracket string</li>
<li>If <i>S</i> is a balanced bracket string, so is <i>(S)</i></li>
<li>If <i>S</i> and <i>T</i> are balanced bracket strings, so is <i>ST</i></li>
</ul>
Print in lexicographical order. '(' appears before ')' in lexicographical orderThe single line of input containing an integer N.
1 <= N <= 15Print all possible balanced bracket strings of length 2*N in a separate line.Sample Input 1:
1
Sample Output 1:
()
Sample Input 2:
3
Sample Output 2:
((()))
(()())
()(())
()()()
Explanation:
It is printed in lexicographical order ., I have written this Solution Code: #include "bits/stdc++.h"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
vector<string> rec(int n){
if(n == 1){
string t = "()";
vector<string> v;
v.push_back(t);
return v;
}
vector<string> v = rec(n-1);
vector<string> cur;
for(auto i: v){
string t = "(" + i + ")";
cur.push_back(t);
}
for(auto i: v){
string t = "()" + i;
cur.push_back(t);
}
return cur;
}
void solve(){
int n; cin >> n;
vector<string> v = rec(n);
for(auto i: v)
cout << i << endl;
}
void testcases(){
int tt = 1;
//cin >> tt;
while(tt--){
solve();
}
}
signed main() {
testcases();
return 0;
} , In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, print all balanced bracket strings of length 2*N.
A bracket string is a string that contains only '(' and ')' as its characters.
<ul>
<li>Empty string is a balanced bracket string</li>
<li>If <i>S</i> is a balanced bracket string, so is <i>(S)</i></li>
<li>If <i>S</i> and <i>T</i> are balanced bracket strings, so is <i>ST</i></li>
</ul>
Print in lexicographical order. '(' appears before ')' in lexicographical orderThe single line of input containing an integer N.
1 <= N <= 15Print all possible balanced bracket strings of length 2*N in a separate line.Sample Input 1:
1
Sample Output 1:
()
Sample Input 2:
3
Sample Output 2:
((()))
(()())
()(())
()()()
Explanation:
It is printed in lexicographical order ., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static ArrayList premutaionsB(ArrayList<String> arr, int n){
if(n == 1)
return arr;
else{
ArrayList<String> arr2 = new ArrayList<>();
for(int i=0;i<arr.size();i++)
arr2.add("(" + arr.get(i) + ")");
for(int i=0;i<arr.size();i++)
arr2.add("()" + arr.get(i));
return premutaionsB(arr2, n-1);
}
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<String> arr = new ArrayList<>();
arr.add("()");
arr = premutaionsB(arr, n);
for(int i=0;i<arr.size();i++)
System.out.println(arr.get(i));
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number N for each i (1 < = i < = N), you have to print the number except :-
For each multiple of 3, print "Newton" instead of the number.
For each multiple of 5, print "School" instead of the number.
For numbers that are multiples of both 3 and 5, print "NewtonSchool" instead of the number.The first line of the input contains N.
<b>Constraints</b>
1 < = N < = 1000
Print N space separated number or Newton School according to the condition.Sample Input:-
3
Sample Output:-
1 2 Newton
Sample Input:-
5
Sample Output:-
1 2 Newton 4 School, I have written this Solution Code: n=int(input())
for i in range(1,n+1):
if i%3==0 and i%5==0:
print("NewtonSchool",end=" ")
elif i%3==0:
print("Newton",end=" ")
elif i%5==0:
print("School",end=" ")
else:
print(i,end=" "), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number N for each i (1 < = i < = N), you have to print the number except :-
For each multiple of 3, print "Newton" instead of the number.
For each multiple of 5, print "School" instead of the number.
For numbers that are multiples of both 3 and 5, print "NewtonSchool" instead of the number.The first line of the input contains N.
<b>Constraints</b>
1 < = N < = 1000
Print N space separated number or Newton School according to the condition.Sample Input:-
3
Sample Output:-
1 2 Newton
Sample Input:-
5
Sample Output:-
1 2 Newton 4 School, I have written this Solution Code: import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
static void NewtonSchool(int n){
for(int i=1;i<=n;i++){
if(i%3==0 && i%5==0){System.out.print("NewtonSchool ");}
else if(i%5==0){System.out.print("School ");}
else if(i%3==0){System.out.print("Newton ");}
else{System.out.print(i+" ");}
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int x= sc.nextInt();
NewtonSchool(x);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara has guests coming over to her house for dinner. She has a circular dining table of radius R and circular plates of radius r. Now she wonders if her table has enough space for all the guests, considering each guest takes one plate and the plate should lie completely inside the table.The input contains three space- separated integers N(Number of guests), R, and r.
Constraints:-
1 <= N <= 100
1 <= r, R <= 1000Print "Yes" if there is enough space, else print "No".Sample Input:-
4 10 4
Sample Output:-
Yes
Sample Input:-
5 10 4
Sample Output:-
No, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String a[] = br.readLine().split(" ");
double n = Integer.parseInt(a[0]);
double R = Integer.parseInt(a[1]);
double r = Integer.parseInt(a[2]);
R=R-r;
double count = 0;
double d = Math.asin(r/R);
count = Math.PI/d;
if(n<=count)
System.out.print("Yes");
else
System.out.print("No");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara has guests coming over to her house for dinner. She has a circular dining table of radius R and circular plates of radius r. Now she wonders if her table has enough space for all the guests, considering each guest takes one plate and the plate should lie completely inside the table.The input contains three space- separated integers N(Number of guests), R, and r.
Constraints:-
1 <= N <= 100
1 <= r, R <= 1000Print "Yes" if there is enough space, else print "No".Sample Input:-
4 10 4
Sample Output:-
Yes
Sample Input:-
5 10 4
Sample Output:-
No, I have written this Solution Code: import math
arr = list(map(int, input().split()))
n = arr[0]
R = arr[1]
r = arr[2]
if(r>R or n>1 and (R-r)*math.sin(math.acos(-1.0)/n)+1e-8<r):
print("No")
else:
print("Yes"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara has guests coming over to her house for dinner. She has a circular dining table of radius R and circular plates of radius r. Now she wonders if her table has enough space for all the guests, considering each guest takes one plate and the plate should lie completely inside the table.The input contains three space- separated integers N(Number of guests), R, and r.
Constraints:-
1 <= N <= 100
1 <= r, R <= 1000Print "Yes" if there is enough space, else print "No".Sample Input:-
4 10 4
Sample Output:-
Yes
Sample Input:-
5 10 4
Sample Output:-
No, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main()
{
int R,r,n;
cin>>n>>R>>r;
cout<<(r>R || n>1&& (R-r)*sin(acos(-1.0)/n)+1e-8<r ?"No":"Yes");
return 0;
}
//1340
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive integer N, your task is to print a right-angle triangle pattern of consecutive numbers of height N.
See the example for a better understanding.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>pattern()</b> that takes integer n as a parameter.
Constraint:
1 <= N <= 100Print a right angle triangle of numbers of height N.Sample Input:
5
Sample Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Sample Input:
2
Sample Output:
1
1 2, I have written this Solution Code: static void pattern(int n){
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
System.out.print(j + " ");
}
System.out.println();
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive integer N, your task is to print a right-angle triangle pattern of consecutive numbers of height N.
See the example for a better understanding.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>pattern()</b> that takes integer n as a parameter.
Constraint:
1 <= N <= 100Print a right angle triangle of numbers of height N.Sample Input:
5
Sample Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Sample Input:
2
Sample Output:
1
1 2, I have written this Solution Code:
void patternPrinting(int n){
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
printf("%d ",j);
}
printf("\n");
}
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive integer N, your task is to print a right-angle triangle pattern of consecutive numbers of height N.
See the example for a better understanding.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>pattern()</b> that takes integer n as a parameter.
Constraint:
1 <= N <= 100Print a right angle triangle of numbers of height N.Sample Input:
5
Sample Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Sample Input:
2
Sample Output:
1
1 2, I have written this Solution Code: function pattern(n) {
// write code herenum
for(let i = 1;i<=n;i++){
let str = ''
for(let k = 1; k <= i;k++){
if(k === 1) {
str += `${k}`
}else{
str += ` ${k}`
}
}
console.log(str)
}
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive integer N, your task is to print a right-angle triangle pattern of consecutive numbers of height N.
See the example for a better understanding.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>pattern()</b> that takes integer n as a parameter.
Constraint:
1 <= N <= 100Print a right angle triangle of numbers of height N.Sample Input:
5
Sample Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Sample Input:
2
Sample Output:
1
1 2, I have written this Solution Code:
void patternPrinting(int n){
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
printf("%d ",j);
}
printf("\n");
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a positive integer N, your task is to print a right-angle triangle pattern of consecutive numbers of height N.
See the example for a better understanding.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>pattern()</b> that takes integer n as a parameter.
Constraint:
1 <= N <= 100Print a right angle triangle of numbers of height N.Sample Input:
5
Sample Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Sample Input:
2
Sample Output:
1
1 2, I have written this Solution Code: def patternPrinting(n):
for i in range(1,n+1):
for j in range (1,i+1):
print(j,end=' ')
print()
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given three integers A, B, and C, your task is to print the sum of these three integers.The input contains 3 integers separated by spaces A, B, and C.
Constraints:-
1 <= A, B, C <= 100Print the sum of A, B and C.Sample Input
1 2 3
Sample Output:-
6
Sample Input:-
5 4 2
Sample Output:-
11, I have written this Solution Code: static void simpleSum(int a, int b, int c){
System.out.println(a+b+c);
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given three integers A, B, and C, your task is to print the sum of these three integers.The input contains 3 integers separated by spaces A, B, and C.
Constraints:-
1 <= A, B, C <= 100Print the sum of A, B and C.Sample Input
1 2 3
Sample Output:-
6
Sample Input:-
5 4 2
Sample Output:-
11, I have written this Solution Code: void simpleSum(int a, int b, int c){
cout<<a+b+c;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given three integers A, B, and C, your task is to print the sum of these three integers.The input contains 3 integers separated by spaces A, B, and C.
Constraints:-
1 <= A, B, C <= 100Print the sum of A, B and C.Sample Input
1 2 3
Sample Output:-
6
Sample Input:-
5 4 2
Sample Output:-
11, I have written this Solution Code: x = input()
a, b, c = x.split()
a = int(a)
b = int(b)
c = int(c)
print(a+b+c), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Newton wants to take revenge from two apples fallen on his head. So, he applies force F<sub>1</sub> on first apple (mass M<sub>1</sub>) resulting in acceleration of A<sub>1</sub> and F<sub>2</sub> on second apple (mass M<sub>2</sub>) resulting in acceleration of A<sub>2</sub>. Given M<sub>1</sub>, A<sub>1</sub>, M<sub>2</sub>, A<sub>2</sub>. Calculate total force applied by him on two apples.
<b>Note:</b> F = M*A is the equation of relation between force, mass and acceleration.First line contains four integers M<sub>1</sub>, A<sub>1</sub>, M<sub>2</sub>, A<sub>2</sub>.
1 <= M<sub>1</sub>, A<sub>1</sub>, M<sub>2</sub>, A<sub>2</sub> <= 100Output total force applied by Newton.INPUT:
1 2 3 4
OUTPUT:
14
Explanation:
Total force is equal to 1*2 + 3*4 = 14., I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
int main(){
int m1,a1,m2,a2;
cin >> m1 >> a1 >> m2 >> a2;
cout << (m1*a1)+(m2*a2) << endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: When learning a new language, we first learn to output some messages. Here, we will start with the famous <b>"Hello World"</b> message. Now, here you are given a function to complete. <i>Don't worry about the ins and outs of functions, <b>just add the printing command to print "Hello World", </b></i>.your task is to just print "Hello World", without the quotes.Hello WorldHello World must be printed., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
System.out.print("Hello World");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: When learning a new language, we first learn to output some messages. Here, we will start with the famous <b>"Hello World"</b> message. Now, here you are given a function to complete. <i>Don't worry about the ins and outs of functions, <b>just add the printing command to print "Hello World", </b></i>.your task is to just print "Hello World", without the quotes.Hello WorldHello World must be printed., I have written this Solution Code: def print_fun():
print ("Hello World")
def main():
print_fun()
if __name__ == '__main__':
main(), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: John has N candies. He wants to crush all of them. He feels that it would be boring to crush the candies randomly, so he found a method to crush them. He divides these candies into a minimum number of groups such that no group contains more than 3 candies. He crushes one candy from each group. If there are G groups in a single step, then the cost incurred in crushing a single candy for that step is G dollars. After candy from each group is crushed, he takes all the remaining candies and repeats the process until he has no candies left. He hasn't started crushing yet, but he wants to know how much the total cost would be incurred. Can you help him?
You have to answer Q-independent queries.The first line of input contains a single integer, Q denoting the number of queries.
Next, Q lines contain a single integer N denoting the number of candies John has.
<b>Constraints</b>
1 <= Q <= 5 * 10^4
1 <= N <= 10^9Print Q lines containing total cost incurred for each query.Sample Input 1:
1
4
Sample Output 1:
6
<b>Explanation:</b>
Query 1: First step John divides the candies into two groups of 3 and 1 candy respectively. Crushing one-one candy from both groups would cost him 2x2 = 4 dollars. He is now left with 2 candies. He divides it into one group. He crushes one candy for 1 dollar. Now, he is left with 1 candy. He crushes the last candy for 1 dollar. So, the total cost incurred is 4+1+1 = 6 dollars., I have written this Solution Code: #include "bits/stdc++.h"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int cost(int n){
if(n == 0) return 0;
int g = (n-1)/3 + 1;
return g*g + cost(n-g);
}
signed main() {
IOS;
clock_t start = clock();
int q; cin >> q;
while(q--){
int n;
cin >> n;
cout << cost(n) << endl;
}
cerr << (double)(clock() - start)*1000/CLOCKS_PER_SEC << " ms" << endl;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: John has N candies. He wants to crush all of them. He feels that it would be boring to crush the candies randomly, so he found a method to crush them. He divides these candies into a minimum number of groups such that no group contains more than 3 candies. He crushes one candy from each group. If there are G groups in a single step, then the cost incurred in crushing a single candy for that step is G dollars. After candy from each group is crushed, he takes all the remaining candies and repeats the process until he has no candies left. He hasn't started crushing yet, but he wants to know how much the total cost would be incurred. Can you help him?
You have to answer Q-independent queries.The first line of input contains a single integer, Q denoting the number of queries.
Next, Q lines contain a single integer N denoting the number of candies John has.
<b>Constraints</b>
1 <= Q <= 5 * 10^4
1 <= N <= 10^9Print Q lines containing total cost incurred for each query.Sample Input 1:
1
4
Sample Output 1:
6
<b>Explanation:</b>
Query 1: First step John divides the candies into two groups of 3 and 1 candy respectively. Crushing one-one candy from both groups would cost him 2x2 = 4 dollars. He is now left with 2 candies. He divides it into one group. He crushes one candy for 1 dollar. Now, he is left with 1 candy. He crushes the last candy for 1 dollar. So, the total cost incurred is 4+1+1 = 6 dollars., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
long q = Long.parseLong(br.readLine());
while(q-->0)
{
long N = Long.parseLong(br.readLine());
System.out.println(candyCrush(N,0,0));
}
}
static long candyCrush(long N, long cost,long group)
{
if(N==0)
{
return cost;
}
if(N%3==0)
{
group = N/3;
cost = cost + (group*group);
return candyCrush(N-group,cost,0);
}
else
{
group = (N/3)+1;
cost = cost + (group*group);
return candyCrush(N-group,cost,0);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a weighted undirected graph.Task is to find the shortest path from source vertex (vertex number 1) to all other vertices from 2 to n.Given 2 integers N and M. N represents the number of vertices in the graph. M represents the number of edges between any 2 vertices.
Then M lines follow, each line has 2 space separated integers a, b where a and b represents an edge from vertex a to vertex b and the weight of that edge = (a+b)%1000.
Constraints
1<=N<=100000
1<=M<=1000000Print the shortest distances from the source vertex (vertex number 1) to all other vertices from 2 to n in separate line. Print "-1" in case the vertex can't be reached form the source vertex.Sample Input
4 5
1 2
1 4
4 2
4 3
2 3
Sample Output
3
8
5
, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main(String args[] ) throws Exception {
int n,m;
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line);
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
ArrayList<ArrayList<int[]>> graph = new ArrayList<>(n+1);
for ( int i= 0; i <= n; i++){
graph.add( new ArrayList<int[]>());
}
for ( int i = 0; i < m; i++){
int u,v,w;
line = br.readLine();
if ( line == null)
continue;
st = new StringTokenizer(line);
u = Integer.parseInt( st.nextToken());
v = Integer.parseInt( st.nextToken());
w=(u+v)%1000;
graph.get(u).add( new int[]{v,w});
graph.get(v).add( new int[]{u,w});
}
long[] dist = Dijkstra(graph,1);
for( int i = 2; i <= n ; i++){
if(dist[i]==9223372036854775807L){
System.out.println("-1");
}
else
System.out.println(dist[i]);
}
}
private static long[] Dijkstra( ArrayList<ArrayList<int[]>> graph, int source){
int n = graph.size();
long[] dist = new long[n];
boolean[] visited = new boolean[n];
Arrays.fill(dist,Long.MAX_VALUE);
PriorityQueue<long[]> queue = new PriorityQueue<>( (long[] i1,long[] i2)->{
if( i1[1] < i2[1])
return -1;
return 1;
});
queue.add(new long[]{source,0});
while ( !queue.isEmpty()){
long[] cn = queue.remove();
if( visited[(int)cn[0]] ){
continue;
}
visited[(int)cn[0]] = true;
dist[(int)cn[0]] = cn[1];
for( int[] neighbour : graph.get((int)cn[0])){
if ( !visited[neighbour[0]] ){
long newdistance = cn[1] + neighbour[1];
if ( newdistance < dist[neighbour[0]]){
dist[neighbour[0]] = newdistance;
queue.add( new long[]{neighbour[0],newdistance});
}
}
}
}
return dist;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a weighted undirected graph.Task is to find the shortest path from source vertex (vertex number 1) to all other vertices from 2 to n.Given 2 integers N and M. N represents the number of vertices in the graph. M represents the number of edges between any 2 vertices.
Then M lines follow, each line has 2 space separated integers a, b where a and b represents an edge from vertex a to vertex b and the weight of that edge = (a+b)%1000.
Constraints
1<=N<=100000
1<=M<=1000000Print the shortest distances from the source vertex (vertex number 1) to all other vertices from 2 to n in separate line. Print "-1" in case the vertex can't be reached form the source vertex.Sample Input
4 5
1 2
1 4
4 2
4 3
2 3
Sample Output
3
8
5
, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
#define pu push_back
#define fi first
#define se second
#define mp make_pair
#define int long long
#define pii pair<int,int>
#define mm (s+e)/2
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(int i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define sz 200000
vector<int> NEB[sz],wt[sz];
int dist[sz];
int vis[sz];
signed main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
int c=(a+b)%1000;
NEB[a].pu(b);
NEB[b].pu(a);
wt[a].pu(c);
wt[b].pu(c);
}
for(int i=1;i<=n;i++)
{
dist[i]=1000000000;
}
multiset<pii> ss;
ss.insert(mp(0,1));
dist[1]=0;
while(ss.size()>0)
{
pii xx=*ss.begin();
int a=xx.se;
ss.erase(ss.begin());
if(vis[a]==1) continue;
vis[a]=1;
int ww=dist[a];
for(int i=0;i<NEB[a].size();i++)
{
int x=NEB[a][i];
int y=wt[a][i];
if(dist[x]>dist[a]+y)
{
dist[x]=dist[a]+y;
ss.insert(mp(dist[x],x));
}
}
}
for(int i=2;i<=n;i++)
{ if(dist[i]>=1000000000) cout<<-1<<"\n";
else cout<<dist[i]<<"\n";
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N points on 2D plane, you have to setup a camp at a point such that sum of Manhattan distance all the points from that point is minimum. If there are many such points you have to find the point with minimum X coordinate and if there are many points with same X coordinate, you have to minimize Y coordinate.
Manhattan distance between points (x1, y1) and (x2, y2) = |x1 - x2| + |y1 - y2|.First line of input contains N.
Next N lines contains two space separated integers denoting the ith coordinate.
Constraints:
1 <= N <= 100000
1 <= X[i], Y[i] <= 1000000000
Note:- the camp can overlap with the given points and the given points can also overlap(you have to consider overlapping points separately).Print two space separated integers, denoting the X and Y coordinate of the camp.Sample Input
3
3 3
1 1
3 2
Sample Output
3 2
Explanation:
Sum of distances = 1 + 3 + 0 = 4
This is the minimum distance possible., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int arr[] = new int[n];
int brr[] = new int[n];
for(int i=0;i<n;i++){
String str[] = br.readLine().split(" ");
arr[i] = Integer.parseInt(str[0]);
brr[i] = Integer.parseInt(str[1]);
}
Arrays.sort(arr);
Arrays.sort(brr);
int m=0;
if(n%2==0){
m = n/2;
}else{
m = (n/2)+1;
}
System.out.println(arr[m-1]+" "+brr[m-1]);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N points on 2D plane, you have to setup a camp at a point such that sum of Manhattan distance all the points from that point is minimum. If there are many such points you have to find the point with minimum X coordinate and if there are many points with same X coordinate, you have to minimize Y coordinate.
Manhattan distance between points (x1, y1) and (x2, y2) = |x1 - x2| + |y1 - y2|.First line of input contains N.
Next N lines contains two space separated integers denoting the ith coordinate.
Constraints:
1 <= N <= 100000
1 <= X[i], Y[i] <= 1000000000
Note:- the camp can overlap with the given points and the given points can also overlap(you have to consider overlapping points separately).Print two space separated integers, denoting the X and Y coordinate of the camp.Sample Input
3
3 3
1 1
3 2
Sample Output
3 2
Explanation:
Sum of distances = 1 + 3 + 0 = 4
This is the minimum distance possible., I have written this Solution Code: n = int(input())
x = []
y = []
for _ in range(n):
tempX,tempY = map(int,input().split())
x.append(tempX)
y.append(tempY)
x.sort()
y.sort()
print(x[(n-1)//2], y[(n-1)//2]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given N points on 2D plane, you have to setup a camp at a point such that sum of Manhattan distance all the points from that point is minimum. If there are many such points you have to find the point with minimum X coordinate and if there are many points with same X coordinate, you have to minimize Y coordinate.
Manhattan distance between points (x1, y1) and (x2, y2) = |x1 - x2| + |y1 - y2|.First line of input contains N.
Next N lines contains two space separated integers denoting the ith coordinate.
Constraints:
1 <= N <= 100000
1 <= X[i], Y[i] <= 1000000000
Note:- the camp can overlap with the given points and the given points can also overlap(you have to consider overlapping points separately).Print two space separated integers, denoting the X and Y coordinate of the camp.Sample Input
3
3 3
1 1
3 2
Sample Output
3 2
Explanation:
Sum of distances = 1 + 3 + 0 = 4
This is the minimum distance possible., I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
cin>>n;
int x[n],y[n];
for(int i=0;i<n;++i){
cin>>x[i]>>y[i];
}
sort(x,x+n);
sort(y,y+n);
cout<<x[(n-1)/2]<<" "<<y[(n-1)/2];
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a program to find the roots of a quadratic equation.
<b>Note</b>: Try to do it using Switch Case.
<b>Quadratic equations</b> are the polynomial equations of degree 2 in one variable of type f(x) = ax<sup>2</sup> + bx + c = 0 where a, b, c, ∈ R and a ≠ 0. It is the general form of a quadratic equation where 'a' is called the leading coefficient and 'c' is called the absolute term of f (x).The first line of the input contains the three integer values a, b, and c of equation ax^2 + bx + c.
<b>Constraints</b>
1 ≤ a, b, c ≤ 50Print the two roots in two different lines and for imaginary roots print real and imaginary part of one root with (+/- and i )sign in between in one line and other in next line. For clarity see sample Output 2.
<b>Note</b> Imaginary roots can also be there and roots are considered upto 2 decimal places.Sample Input 1 :
4 -2 -10
Sample Output 2 :
1.85
-1.35
Sample Input 2 :
2 1 10
Sample Output 2:
-0.25+i2.22
-0.25-i2.22, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine().toString();
String[] str = s.split(" ");
float a=Float.parseFloat(str[0]);
float b=Float.parseFloat(str[1]);
float c=Float.parseFloat(str[2]);
float div = (float)(b*b-4*a*c);
if(div>0.0){
float alpha= (-b+(float)Math.sqrt(div))/(2*a);
float beta= (-b-(float)Math.sqrt(div))/(2*a);
System.out.printf("%.2f\n",alpha);
System.out.printf("%.2f",beta);
}
else{
float rp=-b/(2*a);
float ip=(float)Math.sqrt(-div)/(2*a);
System.out.printf("%.2f+i%.2f\n",rp,ip);
System.out.printf("%.2f-i%.2f\n",rp,ip);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a program to find the roots of a quadratic equation.
<b>Note</b>: Try to do it using Switch Case.
<b>Quadratic equations</b> are the polynomial equations of degree 2 in one variable of type f(x) = ax<sup>2</sup> + bx + c = 0 where a, b, c, ∈ R and a ≠ 0. It is the general form of a quadratic equation where 'a' is called the leading coefficient and 'c' is called the absolute term of f (x).The first line of the input contains the three integer values a, b, and c of equation ax^2 + bx + c.
<b>Constraints</b>
1 ≤ a, b, c ≤ 50Print the two roots in two different lines and for imaginary roots print real and imaginary part of one root with (+/- and i )sign in between in one line and other in next line. For clarity see sample Output 2.
<b>Note</b> Imaginary roots can also be there and roots are considered upto 2 decimal places.Sample Input 1 :
4 -2 -10
Sample Output 2 :
1.85
-1.35
Sample Input 2 :
2 1 10
Sample Output 2:
-0.25+i2.22
-0.25-i2.22, I have written this Solution Code: import math
a,b,c = map(int, input().split(' '))
disc = (b ** 2) - (4*a*c)
sq = disc ** 0.5
if disc > 0:
print("{:.2f}".format((-b + sq)/(2*a)))
print("{:.2f}".format((-b - sq)/(2*a)))
elif disc == 0:
print("{:.2f}".format(-b/(2*a)))
elif disc < 0:
r1 = complex((-b + sq)/(2*a))
r2 = complex((-b - sq)/(2*a))
print("{:.2f}+i{:.2f}".format(r1.real, abs(r1.imag)))
print("{:.2f}-i{:.2f}".format(r2.real, abs(r2.imag))), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a program to find the roots of a quadratic equation.
<b>Note</b>: Try to do it using Switch Case.
<b>Quadratic equations</b> are the polynomial equations of degree 2 in one variable of type f(x) = ax<sup>2</sup> + bx + c = 0 where a, b, c, ∈ R and a ≠ 0. It is the general form of a quadratic equation where 'a' is called the leading coefficient and 'c' is called the absolute term of f (x).The first line of the input contains the three integer values a, b, and c of equation ax^2 + bx + c.
<b>Constraints</b>
1 ≤ a, b, c ≤ 50Print the two roots in two different lines and for imaginary roots print real and imaginary part of one root with (+/- and i )sign in between in one line and other in next line. For clarity see sample Output 2.
<b>Note</b> Imaginary roots can also be there and roots are considered upto 2 decimal places.Sample Input 1 :
4 -2 -10
Sample Output 2 :
1.85
-1.35
Sample Input 2 :
2 1 10
Sample Output 2:
-0.25+i2.22
-0.25-i2.22, I have written this Solution Code: /**
* Author : tourist1256
* Time : 2022-01-19 02:44:22
**/
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
int main() {
float a, b, c;
float root1, root2, imaginary;
float discriminant;
scanf("%f%f%f", &a, &b, &c);
discriminant = (b * b) - (4 * a * c);
switch (discriminant > 0) {
case 1:
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("%.2f\n%.2f", root1, root2);
break;
case 0:
switch (discriminant < 0) {
case 1:
root1 = root2 = -b / (2 * a);
imaginary = sqrt(-discriminant) / (2 * a);
printf("%.2f + i%.2f\n%.2f - i%.2f", root1, imaginary, root2, imaginary);
break;
case 0:
root1 = root2 = -b / (2 * a);
printf("%.2f\n%.2f", root1, root2);
break;
}
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S consisting of digits between 1 and 9. Rearrange the string such that the number of even substrings it contains is maximised. A substring is said to be even if the number it represents is even.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>solve()</b> that takes the string S as parameter.
<b>Constraints</b>
1<=|S|<=1000
S only contains digits between 1 and 9 (both inclusive).Return the number of even substrings present in the string after rearranging it such that the number is maximised.Sample Input:
1232
Sample Output:
7
We will rearrange the string to "1322". Now, the seven even substrings are "132", "32", "2", "2", "1232", "232", "32". Two substrings are considered different if at least one of the starting or ending index differs from the other., I have written this Solution Code:
class Solution {
public long solve(String S) {
int e = 0;
for (int i = 0; i < S.length(); i++) {
int y = S.charAt(i) - '0';
if (y % 2 == 0) {
e++;
}
}
long ans = 0;
for (int i = S.length(); i >= 0; i--) {
if (e > 0) {
ans += i;
e--;
}
}
return ans;
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A number X (X>=0) is called strange if the sum of its digits is divisible by 9. Given an integer N, your task is to find the Nth strange number.The input contains a single line containing the value of N.
Constraints:-
1 <= N <= 1000Print the Nth strange number.Sample Input:-
3
Sample Output:-
18
Explanation:-
0, 9, and 18 are the first three strange numbers.
Sample Input:-
2
Sample Output:-
9, I have written this Solution Code: import java.util.*;
import java.io.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x=sc.nextInt();
int ans = 9 * (x-1);
System.out.print(ans);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A number X (X>=0) is called strange if the sum of its digits is divisible by 9. Given an integer N, your task is to find the Nth strange number.The input contains a single line containing the value of N.
Constraints:-
1 <= N <= 1000Print the Nth strange number.Sample Input:-
3
Sample Output:-
18
Explanation:-
0, 9, and 18 are the first three strange numbers.
Sample Input:-
2
Sample Output:-
9, I have written this Solution Code:
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 1000001
#define MOD 1000000000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int cnt[max1];
signed main(){
int n;
cin>>n;
out((n-1)*9);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A number X (X>=0) is called strange if the sum of its digits is divisible by 9. Given an integer N, your task is to find the Nth strange number.The input contains a single line containing the value of N.
Constraints:-
1 <= N <= 1000Print the Nth strange number.Sample Input:-
3
Sample Output:-
18
Explanation:-
0, 9, and 18 are the first three strange numbers.
Sample Input:-
2
Sample Output:-
9, I have written this Solution Code: a=int(input())
print(9*(a-1)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a year(an integer variable) as input, find if it is a leap year or not.
Note: Leap year is the year that is multiple of 4. But, multiples of 100 which are not multiples of 400 are not leap years.The input contains a single integer N
<b>Constraint:</b>
1 <= n <= 10<sup>4</sup>Print "YES" if the year is a leap year else print "NO".Sample Input:
2000
Sample Output:
YES
Sample Input:
2003
Sample Output:
NO
Sample Input:
1900
Sample Output:
NO, I have written this Solution Code:
function LeapYear(year){
// write code here
// return the output using return keyword
// do not use console.log here
if ((0 != year % 4) || ((0 == year % 100) && (0 != year % 400))) {
return 0;
} else {
return 1
}
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a year(an integer variable) as input, find if it is a leap year or not.
Note: Leap year is the year that is multiple of 4. But, multiples of 100 which are not multiples of 400 are not leap years.The input contains a single integer N
<b>Constraint:</b>
1 <= n <= 10<sup>4</sup>Print "YES" if the year is a leap year else print "NO".Sample Input:
2000
Sample Output:
YES
Sample Input:
2003
Sample Output:
NO
Sample Input:
1900
Sample Output:
NO, I have written this Solution Code: year = int(input())
if year % 4 == 0 and not year % 100 == 0 or year % 400 == 0:
print("YES")
else:
print("NO"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a year(an integer variable) as input, find if it is a leap year or not.
Note: Leap year is the year that is multiple of 4. But, multiples of 100 which are not multiples of 400 are not leap years.The input contains a single integer N
<b>Constraint:</b>
1 <= n <= 10<sup>4</sup>Print "YES" if the year is a leap year else print "NO".Sample Input:
2000
Sample Output:
YES
Sample Input:
2003
Sample Output:
NO
Sample Input:
1900
Sample Output:
NO, I have written this Solution Code: import java.util.Scanner;
class Main {
public static void main (String[] args)
{
//Capture the user's input
Scanner scanner = new Scanner(System.in);
//Storing the captured value in a variable
int side = scanner.nextInt();
int area = LeapYear(side);
if(area==1){
System.out.println("YES");}
else{
System.out.println("NO");}
}
static int LeapYear(int year){
if(year%400==0){return 1;}
if(year%100 != 0 && year%4==0){return 1;}
else {
return 0;}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a big number in form of a string A of characters from 0 to 9.
Check whether the given number is divisible by 30 .The first argument is the string A.
<b>Constraints</b>
1 ≤ |A| ≤ 10<sup>5</sup>Return "Yes" if it is divisible by 30 and "No" otherwise. Sample Input :
3033330
Sample Output:
Yes, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String a= br.readLine();
int sum=0;
int n=a.length();
int s=0;
for(int i=0; i<n; i++){
sum=sum+ (a.charAt(i) - '0');
if(i == n-1){
s= (a.charAt(i) - '0');
}
}
if(sum%3==0 && s==0){
System.out.print("Yes");
}else{
System.out.print("No");
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a big number in form of a string A of characters from 0 to 9.
Check whether the given number is divisible by 30 .The first argument is the string A.
<b>Constraints</b>
1 ≤ |A| ≤ 10<sup>5</sup>Return "Yes" if it is divisible by 30 and "No" otherwise. Sample Input :
3033330
Sample Output:
Yes, I have written this Solution Code: /**
* Author : tourist1256
* Time : 2022-02-10 11:06:49
**/
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
int solve(string a) {
int n = a.size();
int sum = 0;
if (a[n - 1] != '0') {
return 0;
}
for (auto &it : a) {
sum += (it - '0');
}
debug(sum % 3);
if (sum % 3 == 0) {
return 1;
}
return 0;
}
int32_t main() {
ios_base::sync_with_stdio(NULL);
cin.tie(0);
string str;
cin >> str;
int res = solve(str);
if (res) {
cout << "Yes\n";
} else {
cout << "No\n";
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a big number in form of a string A of characters from 0 to 9.
Check whether the given number is divisible by 30 .The first argument is the string A.
<b>Constraints</b>
1 ≤ |A| ≤ 10<sup>5</sup>Return "Yes" if it is divisible by 30 and "No" otherwise. Sample Input :
3033330
Sample Output:
Yes, I have written this Solution Code: A=int(input())
if A%30==0:
print("Yes")
else:
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a charity which has N people. Penny wants to donate some of her clothes to the charity in such a way that all people receive equal clothes and each individual receives <b> more than 1 </b>. If she has M clothes with her what is the maximum number of clothes one individual can get?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Charity()</b> that takes integers N, and M as arguments.
Constraints:-
1 <= M, N <= 1000Return the maximum number of clothes one individual can get if it is impossible to distribute clothes return -1.Sample Input
6 20
Sample Output
3
Sample Input
8 5
Sample Output
-1, I have written this Solution Code: function Charity(n,m) {
// write code here
// do no console.log the answer
// return the output using return keyword
const per = Math.floor(m / n)
return per > 1 ? per : -1
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a charity which has N people. Penny wants to donate some of her clothes to the charity in such a way that all people receive equal clothes and each individual receives <b> more than 1 </b>. If she has M clothes with her what is the maximum number of clothes one individual can get?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Charity()</b> that takes integers N, and M as arguments.
Constraints:-
1 <= M, N <= 1000Return the maximum number of clothes one individual can get if it is impossible to distribute clothes return -1.Sample Input
6 20
Sample Output
3
Sample Input
8 5
Sample Output
-1, I have written this Solution Code: static int Charity(int n, int m){
int x= m/n;
if(x<=1){return -1;}
return x;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a charity which has N people. Penny wants to donate some of her clothes to the charity in such a way that all people receive equal clothes and each individual receives <b> more than 1 </b>. If she has M clothes with her what is the maximum number of clothes one individual can get?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Charity()</b> that takes integers N, and M as arguments.
Constraints:-
1 <= M, N <= 1000Return the maximum number of clothes one individual can get if it is impossible to distribute clothes return -1.Sample Input
6 20
Sample Output
3
Sample Input
8 5
Sample Output
-1, I have written this Solution Code: int Charity(int n, int m){
int x= m/n;
if(x<=1){return -1;}
return x;
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a charity which has N people. Penny wants to donate some of her clothes to the charity in such a way that all people receive equal clothes and each individual receives <b> more than 1 </b>. If she has M clothes with her what is the maximum number of clothes one individual can get?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Charity()</b> that takes integers N, and M as arguments.
Constraints:-
1 <= M, N <= 1000Return the maximum number of clothes one individual can get if it is impossible to distribute clothes return -1.Sample Input
6 20
Sample Output
3
Sample Input
8 5
Sample Output
-1, I have written this Solution Code: def Charity(N,M):
x = M//N
if x<=1:
return -1
return x
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a charity which has N people. Penny wants to donate some of her clothes to the charity in such a way that all people receive equal clothes and each individual receives <b> more than 1 </b>. If she has M clothes with her what is the maximum number of clothes one individual can get?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Charity()</b> that takes integers N, and M as arguments.
Constraints:-
1 <= M, N <= 1000Return the maximum number of clothes one individual can get if it is impossible to distribute clothes return -1.Sample Input
6 20
Sample Output
3
Sample Input
8 5
Sample Output
-1, I have written this Solution Code: int Charity(int n, int m){
int x= m/n;
if(x<=1){return -1;}
return x;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given the heads of two singly linked lists head1 and head2, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null
For example, the following two linked lists begin to intersect at node c1<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>intersection()</b> that takes the head node of both lists as a parameter.
The first line of the test case contains:
<ul>
<li>the size of the 1st linked list</li>
<li>size of 2nd linked list</li>
<li>the size of the common part of two linked lists</li>
</ul>
The rest of the test case contains:
<ul>
<li>elements of 1st linked list</li>
<li>elements of 2nd linked list</li>
<li>common part of two linked lists</li>
</ul>Return the node of intersectionSample Input:-
4 3 4
1 2 3 4
5 6 7
9 10 11 12
Sample Output:-
9
Explanation:
1 -> 2 -> 3 -> 4
      |
       9 -> 10 -> 11 -> 12
      |
  5 -> 6 -> 7, I have written this Solution Code:
public static Node intersection(Node head1,Node head2){ int aLength = getLength(head1), bLength = getLength(head2);
Node currA = head1, currB = head2;
if (bLength > aLength)
for (int i = 0; i < bLength - aLength; i++) currB = currB.next;
if (aLength > bLength)
for (int i = 0; i < aLength - bLength; i++) currA = currA.next;
while (currA != null && currB != null) {
if (currA == currB) return currA;
currA = currA.next;
currB = currB.next;
}
return null;
}
private static int getLength(Node head) {
Node curr = head;
int len = 0;
while (curr != null) {
curr = curr.next;
len++;
}
return len;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of integers of size N, your task is to find the maximum parity index of this array.
<b>Parity Index is the maximum difference between two indices i and j (1 <= i < j <= N) of an array A such that A<sub>i</sub> < A<sub>j</sub>.</b>The first line contains a single integer N, next line contains N space-separated integers depicting the values of the array.
<b>Constraints:-</b>
1 < = N < = 10<sup>5</sup>
1 < = Arr[i] < = 10<sup>5</sup>Print the maximum value of <b>j- i</b> under the given condition, if no pair satisfies the condition print -1.Sample Input 1:-
5
1 2 3 4 5
Sample Output 1:-
4
Sample Input 2:-
5
5 4 3 2 1
Sample Output 2:-
-1
<b>Explanation 1:</b>
The maximum difference of j<sub>th</sub> - i<sub>th</sub> index is 4:(4<sub>th</sub> - 0<sub>th</sub>), also arr[4] > arr[0]
, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main (String[] args)throws IOException {
Reader sc = new Reader();
int N = sc.nextInt();
int[] arr = new int[N];
for(int i=0;i<N;i++){
arr[i] = sc.nextInt();
}
int max=0;
if(arr[0]<arr[N-1])
System.out.print(N-1);
else{
for(int i=0;i<N-1;i++){
int j = N-1;
while(j>i){
if(arr[i]<arr[j]){
if(max<j-i){
max = j-i;
} break;
}
j--;
}
if(i==j)
break;
if(j==N-1)
break;
}
if(max==0)
System.out.print("-1");
else
System.out.print(max);
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of integers of size N, your task is to find the maximum parity index of this array.
<b>Parity Index is the maximum difference between two indices i and j (1 <= i < j <= N) of an array A such that A<sub>i</sub> < A<sub>j</sub>.</b>The first line contains a single integer N, next line contains N space-separated integers depicting the values of the array.
<b>Constraints:-</b>
1 < = N < = 10<sup>5</sup>
1 < = Arr[i] < = 10<sup>5</sup>Print the maximum value of <b>j- i</b> under the given condition, if no pair satisfies the condition print -1.Sample Input 1:-
5
1 2 3 4 5
Sample Output 1:-
4
Sample Input 2:-
5
5 4 3 2 1
Sample Output 2:-
-1
<b>Explanation 1:</b>
The maximum difference of j<sub>th</sub> - i<sub>th</sub> index is 4:(4<sub>th</sub> - 0<sub>th</sub>), also arr[4] > arr[0]
, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define int long long
/* For a given array arr[],
returns the maximum j – i such that
arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
int maxDiff;
int i, j;
int *LMin = new int[(sizeof(int) * n)];
int *RMax = new int[(sizeof(int) * n)];
/* Construct LMin[] such that
LMin[i] stores the minimum value
from (arr[0], arr[1], ... arr[i]) */
LMin[0] = arr[0];
for (i = 1; i < n; ++i)
LMin[i] = min(arr[i], LMin[i - 1]);
/* Construct RMax[] such that
RMax[j] stores the maximum value from
(arr[j], arr[j+1], ..arr[n-1]) */
RMax[n - 1] = arr[n - 1];
for (j = n - 2; j >= 0; --j)
RMax[j] = max(arr[j], RMax[j + 1]);
/* Traverse both arrays from left to right
to find optimum j - i. This process is similar to
merge() of MergeSort */
i = 0, j = 0, maxDiff = -1;
while (j < n && i < n)
{
if (LMin[i] < RMax[j])
{
maxDiff = max(maxDiff, j - i);
j = j + 1;
}
else
i = i + 1;
}
return maxDiff;
}
// Driver Code
signed main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int maxDiff = maxIndexDiff(a, n);
cout << maxDiff;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of integers of size N, your task is to find the maximum parity index of this array.
<b>Parity Index is the maximum difference between two indices i and j (1 <= i < j <= N) of an array A such that A<sub>i</sub> < A<sub>j</sub>.</b>The first line contains a single integer N, next line contains N space-separated integers depicting the values of the array.
<b>Constraints:-</b>
1 < = N < = 10<sup>5</sup>
1 < = Arr[i] < = 10<sup>5</sup>Print the maximum value of <b>j- i</b> under the given condition, if no pair satisfies the condition print -1.Sample Input 1:-
5
1 2 3 4 5
Sample Output 1:-
4
Sample Input 2:-
5
5 4 3 2 1
Sample Output 2:-
-1
<b>Explanation 1:</b>
The maximum difference of j<sub>th</sub> - i<sub>th</sub> index is 4:(4<sub>th</sub> - 0<sub>th</sub>), also arr[4] > arr[0]
, I have written this Solution Code: n=int(input())
arr=list(map(int,input().split()))
rightMax = [0] * n
rightMax[n - 1] = arr[n - 1]
for i in range(n - 2, -1, -1):
rightMax[i] = max(rightMax[i + 1], arr[i])
maxDist = -2**31
i = 0
j = 0
while (i < n and j < n):
if (rightMax[j] >= arr[i]):
maxDist = max(maxDist, j - i)
j += 1
else:
i += 1
if maxDist==0:
maxDist=-1
print(maxDist), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given three integers A, B, and C, your task is to print the sum of these three integers.The input contains 3 integers separated by spaces A, B, and C.
Constraints:-
1 <= A, B, C <= 100Print the sum of A, B and C.Sample Input
1 2 3
Sample Output:-
6
Sample Input:-
5 4 2
Sample Output:-
11, I have written this Solution Code: static void simpleSum(int a, int b, int c){
System.out.println(a+b+c);
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given three integers A, B, and C, your task is to print the sum of these three integers.The input contains 3 integers separated by spaces A, B, and C.
Constraints:-
1 <= A, B, C <= 100Print the sum of A, B and C.Sample Input
1 2 3
Sample Output:-
6
Sample Input:-
5 4 2
Sample Output:-
11, I have written this Solution Code: void simpleSum(int a, int b, int c){
cout<<a+b+c;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given three integers A, B, and C, your task is to print the sum of these three integers.The input contains 3 integers separated by spaces A, B, and C.
Constraints:-
1 <= A, B, C <= 100Print the sum of A, B and C.Sample Input
1 2 3
Sample Output:-
6
Sample Input:-
5 4 2
Sample Output:-
11, I have written this Solution Code: x = input()
a, b, c = x.split()
a = int(a)
b = int(b)
c = int(c)
print(a+b+c), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: When learning a new language, we first learn to output some message. Here, we'll start with the famous "Hello World" message. There is no input, you just have to print "Hello World".No InputHello WorldExplanation:
Hello World is printed., I have written this Solution Code: a="Hello World"
print(a), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: When learning a new language, we first learn to output some message. Here, we'll start with the famous "Hello World" message. There is no input, you just have to print "Hello World".No InputHello WorldExplanation:
Hello World is printed., I have written this Solution Code: import java.util.*;
import java.io.*;
class Main{
public static void main(String args[]){
System.out.println("Hello World");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a cubic dice with 6 faces. All the individual faces have a numbers printed on them. The numbers are in the range of 1 to 6, like any ordinary dice.
Given a number on one face of the dice , you need to print the number on the opposite face .
NOTE : In a normal dice sum of numbers on opposite faces is 7 .The first line of the input contains a single integer T, denoting the number of test cases. Then T test case follows. Each test case contains a single line of the input containing a positive integer N.
Constraints:
1 <= T <= 100
1 <= N <= 6For each testcase, print the number that is on the opposite side of the given face.Input:
2
6
2
Output:
1
5
Explanation:
Testcase 1: For dice facing number 6 opposite face will have the number 1., I have written this Solution Code: def get_opposite_face(n):
return 7-n
t = int(input())
for n in range(t):
print(get_opposite_face(int(input()))), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a cubic dice with 6 faces. All the individual faces have a numbers printed on them. The numbers are in the range of 1 to 6, like any ordinary dice.
Given a number on one face of the dice , you need to print the number on the opposite face .
NOTE : In a normal dice sum of numbers on opposite faces is 7 .The first line of the input contains a single integer T, denoting the number of test cases. Then T test case follows. Each test case contains a single line of the input containing a positive integer N.
Constraints:
1 <= T <= 100
1 <= N <= 6For each testcase, print the number that is on the opposite side of the given face.Input:
2
6
2
Output:
1
5
Explanation:
Testcase 1: For dice facing number 6 opposite face will have the number 1., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
signed main() {
IOS;
int t; cin >> t;
while(t--){
int n; cin >> n;
cout << 7-n << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a cubic dice with 6 faces. All the individual faces have a numbers printed on them. The numbers are in the range of 1 to 6, like any ordinary dice.
Given a number on one face of the dice , you need to print the number on the opposite face .
NOTE : In a normal dice sum of numbers on opposite faces is 7 .The first line of the input contains a single integer T, denoting the number of test cases. Then T test case follows. Each test case contains a single line of the input containing a positive integer N.
Constraints:
1 <= T <= 100
1 <= N <= 6For each testcase, print the number that is on the opposite side of the given face.Input:
2
6
2
Output:
1
5
Explanation:
Testcase 1: For dice facing number 6 opposite face will have the number 1., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t-->0){
int n=Integer.parseInt(br.readLine());
System.out.println(6-n+1);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.