In this Codechef Divisible by 3 problem-solution Stack likes the number 3 a lot.
He has two non-negative integers AA and BB.
In one operation, Stack can do either of the following:
A:=|A-B|A:=∣A−B∣ (change AA to |A-B|∣A−B∣)
B:=|A-B|B:=∣A−B∣ (change BB to |A-B|∣A−B∣)
Note that |X|∣X∣ denotes absolute value of XX. For example |-7| = 7∣−7∣=7 and |4| = 4∣4∣=4.
Find the minimum number of operations after which at least one integer out of A and B becomes divisible by 3.
Problem solution in Python.
# cook your dish here
for i in range(int(input())):
A, B = [int(i) for i in input().split()]
if A % 3 ==0 or B % 3 == 0:
print(0)
elif A <= B:
if (B-A) % 3 == 0:
print(1)
else:
print(2)
else:
if (A-B) % 3 == 0:
print(1)
else:
print(2)
Problem solution in Java.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 0; i < t; i++){
int a = sc.nextInt();
int b = sc.nextInt();
if(a%3==0||b%3==0){
System.out.println(0);
}else if(Math.abs(a-b)%3==0){
System.out.println(1);
}else{
System.out.println(2);
}
}
// your code goes here
}
}
Problem solution in C++.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define loop(i,a,b) for(int i=a;i<b;i++)
#define range(a) a.begin(),a.end()
#define p(a) push_back(a)
int main() {
// your code goes here
int t;
cin>>t;
while(t--){
ll a,b;
cin>>a>>b;
int count=0;
if(a%3==0 || b%3==0){
cout<<0<<endl;
}
else if(a==b){
cout<<1<<endl;
}
else{
int ans1=a%3;
int ans2=b%3;
if(ans1==ans2){
cout<<1<<endl;
}
else{
cout<<2<<endl;
}
}
}
return 0;
}
Problem solution in C.
#include<stdio.h>
int main()
{
int t,i,a,b,p=0,q=0;
scanf("%d",&t);
for(i=0;i<t;i++){
scanf("%d %d",&a,&b);
while(a%3!=0&&b%3!=0){
if(a>b){
a=a-b;
p++;
}
else{
b=b-a;
p++;
}
if(a%3==0||b%3==0)
break;
}
q=p;
p=0;
printf("%d\n",q);
}
return 0;
}

0 Comments