Code Chef DSA Learning Series : Multiple of 3 - c++

Consider a very long K-digit number N with digits d0, d1, ..., dK-1 (in decimal notation; d0 is the most significant and dK-1 the least significant digit). This number is so large that we can't give it to you on the input explicitly; instead, you are only given its starting digits and a way to construct the remainder of the number.
Specifically, you are given d0 and d1; for each i ≥ 2, di is the sum of all preceding (more significant) digits, modulo 10 — more formally, the following formula must hold:
Determine if N is a multiple of 3.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains three space-separated integers K, d0 and d1.
Output
For each test case, print a single line containing the string "YES" (without quotes) if the number N is a multiple of 3 or "NO" (without quotes) otherwise.
Constraints
1 ≤ T ≤ 1000
2 ≤ K ≤ 1012
1 ≤ d0 ≤ 9
0 ≤ d1 ≤ 9
Example
Input:
3
5 3 4
13 8 1
760399384224 5 1
Output:
NO
YES
YES
Explanation
Example case 1: The whole number N is 34748, which is not divisible by 3, so the answer is NO.
Example case 2: The whole number N is 8198624862486, which is divisible by 3, so the answer is YES.
Question Ended
In this question, in the example test case given, we have k=760399384224, d0=5, and d1=1. Now we know that a number is multiple of 3 if the sum of it’s digits is a multiple of 3. So applying it here, we separate the number n into 3 parts,
Part 1: First 3 digits -> 516 , (5+1+6) mod 3 ==0, so rem1 = 0.
Part 2: Next will be (k-3)/4 times repetition of (2486) ,or,rem2 = ((2+4+8+6)*((k-3)/4))%3= 1
Part 3: the last (k-3)%4 =1 digits which will be 2 (from 2486 repetition) , so rem3 = 2%3=2
So the final answer should be (rem1+rem2+rem3)%3
and I wrote the following code for this logic:
#include<iostream>
#define ll long long
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
ll k;
cin>>k;
int d0,d1;
cin>>d0>>d1;
int d2 = (d0+d1)%10;
int d[4];
d[0] = (d0+d1+d2)%10;
d[1] = (2*d[0])%10;
d[2] = (2*d[1])%10;
d[3] = (2*d[2])%10;
ll rem1 = (d0+d1+d2)%3,rem2,rem3=0;
rem2 = (20*(((k-3)/4)%3))%3;
ll x = (k-3)%4;
if(x!=0)
{
for(int i=0; i<x; ++i)
rem3+=d[i];
rem3 = rem3%3;
}
else
rem3 =0;
if(k==2)
{
rem1 = (d0+d1)%3;
rem2=0;
rem3=0;
}
if((rem1+rem2+rem3)%3==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
Now they’re giving me WA in their test cases. And I cant think of a possible test cases which doesn’t work with this code. So somebody help me out please.

Here's an apparent mismatch. You can probably use this JavaScript code to find more:
function f(k, d0, d1){
let d2 = (d0+d1)%10;
let d = new Array(4).fill(0);
d[0] = (d0+d1+d2)%10;
d[1] = (2*d[0])%10;
d[2] = (2*d[1])%10;
d[3] = (2*d[2])%10;
let rem1 = (d0+d1+d2)%3, rem2, rem3=0;
rem2 = (20*((~~((k-3)/4))%3))%3;
let x = (k-3)%4;
if(x!=0)
{
for(let i=0; i<x; ++i)
rem3+=d[i];
rem3 = rem3%3;
}
else
rem3 =0;
if(k==2)
{
rem1 = (d0+d1)%3;
rem2=0;
rem3=0;
}
if((rem1+rem2+rem3)%3==0)
return true
return false
}
function bruteForce(k, d0, d1){
let d = (d0 + d1) % 10;
let n = 10 * d0 + d1;
for (let i=3; i<=k; i++){
n = 10 * n + d;
d = (2 * d) % 10;
}
return [n % 3 == 0, n];
}
let str = "";
str += "Examples:\n";
str += "(5, 3, 4)\n" + bruteForce(5, 3, 4) + "\n\n";
str += "(13, 8, 1)\n" + bruteForce(13, 8, 1) + "\n\n"
var k = 7;
var mismatch = false;
for (let i=1; i<10; i++){
for (let j=0; j<10; j++){
const _f = f(k, i, j);
const _bruteForce = bruteForce(k, i, j);
if (_bruteForce[0] != _f){
str += "Mismatch:\n" +
`(${ k }, ${ i }, ${ j })\n` +
"f: " + _f +
"\nbruteForce: " + _bruteForce + "\n\n";
mismatch = true;
}
if (mismatch)
break;
}
if (mismatch)
break;
}
console.log(str);

#include <stdio.h>
void isMulti3(long long int K, long long int d0, long long int d1) {
long long int mod1 = (d0 + d1) % 10;
long long int sum_mod1 = d0 + d1 + mod1;
long long int rep = (K-3)/4;
long long int mod2[4];
mod2[0] = (2*mod1) % 10;
mod2[1] = (4*mod1) % 10;
mod2[2] = (8*mod1) % 10;
mod2[3] = (6*mod1) % 10;
long long int sum_mod2 = 0;
for(int i = 0; i < 4; i++) {
sum_mod2 += mod2[i];
}
long long int unrep = (K - 3) % 4;
long long int sum_mod3 = 0;
for(int i = 0; i < unrep; i++) sum_mod3 += mod2[i];
long long int isMod1 = sum_mod1 % 3;
long long int isMod2 = ((rep%3)*(sum_mod2%3)) % 3;
long long int isMod3 = sum_mod3 % 3;
if((isMod1 + (isMod2 + isMod3)%3)% 3 == 0) printf("YES\n");
else printf("NO\n");
}
int main() {
int T;
scanf("%d", &T);
for(int i = 0; i < T; i++) {
long long int K;
long long int d0, d1;
scanf("%lld %lld %lld", &K, &d0, &d1);
if(K == 2) {
if((d0 + d1) % 3 == 0) printf("YES\n");
else printf("NO\n");
}
else isMulti3(K, d0, d1);
}
}
I think you are the same guy who asked the question on the codechef discussion portal.
I answered it there , and I am sharing the link.
[https://discuss.codechef.com/t/dsa-learning-series-multiple-of-3/77174/4?u=nazishkaunain][1]
So the point where you are mistaken is:
You might use the fact:
(a+b+c)mod 3 != a mod 3 + b mod 3 + c mod 3;
But (a + b + c) mod 3 = (a mod 3 + ( b mod 3 + c mod 3) mod 3) mod 3;
And a number n ( n = a + b + c) is divisible by 3 only if n mod 3 = 0 => (a + b + c) mod 3 = 0.

Related

Count of binary numbers from 1 to n

I want to find the number of numbers between 1 and n that are valid numbers in base two (binary).
1 ≤ n ≤ 10^9
For example, suppose n is equal to 101.
Input: n = 101
In this case, the answer is 5
Output: 1, 10, 11, 100, 101 -> 5
Another example
Input: n = 13
Output: 1, 10, 11 -> 3
Here is my code...
#include <iostream>
using namespace std;
int main()
{
int n, c = 0;
cin >> n;
for (int i = 1; i <= n; ++i)
{
int temp = i;
bool flag = true;
while(temp != 0) {
int rem = temp % 10;
if (rem > 1)
{
flag = false;
break;
}
temp /= 10;
}
if (flag)
{
c++;
}
}
cout << c;
return 0;
}
But I want more speed.
(With only one loop or maybe without any loop)
Thanks in advance!
The highest binary number that will fit in a d-digit number d1 d2 ... dn is
b1 b2 ... bn where
bi = 0 if di = 0, and
bi = 1 otherwise.
A trivial implementation using std::to_string:
int max_binary(int input) {
int res = 0;
auto x = std::to_string(input);
for (char di : x) {
int bi = x == '0' ? 0 : 1;
res = 2 * res + bi;
}
return res;
}
Details:
In each step, if the digit was one, then we add 2 to the power of the number of digits we have.
If the number was greater than 1, then all cases are possible for that number of digits, and we can also count that digit itself and change the answer altogether (-1 is because we do not want to calculate the 0).
#include <iostream>
using namespace std;
int main()
{
long long int n, res = 0, power = 1;
cin >> n;
while(n != 0) {
int rem = n % 10;
if (rem == 1) {
res += power;
} else if (rem > 1) {
res = 2 * power - 1;
}
n /= 10;
power *= 2;
}
cout << res;
return 0;
}

If NxM multiplication table put in order, what is number on K position?

If I have multiplication table 3x4
1 2 3 4
2 4 6 8
3 6 9 12
and put all these numbers in the order:
1 2 2 3 3 4 4 6 6 8 9 12
What number at the K position?
For example, if K = 5, then this is number 3.
N and M in the range 1 to 500 000. K is always less then N * M.
I've tried to use binary-search like in this(If an NxM multiplication table is put in order, what is number in the middle?) solution, but there some mistake if desired value not in the middle of sequence.
long findK(long n, long m, long k)
{
long min = 1;
long max = n * m;
long ans = 0;
long prev_sum = 0;
while (min <= max) {
ans = (min + max) / 2;
long sum = 0;
for (int i = 1; i <= m; i++)
{
sum += std::min(ans / i, n);
}
if (prev_sum + 1 == sum) break;
sum--;
if (sum < k) min = ans - 1;
else if (sum > k) max = ans + 1;
else break;
prev_sum = sum;
}
long sum = 0;
for (int i = 1; i <= m; i++)
sum += std::min((ans - 1) / i, n);
if (sum == k) return ans - 1;
else return ans;
}
For example, when N = 1000, M = 1000, K = 876543; expected value is 546970, but returned 546972.
I believe that the breakthrough will lie with counting the quantity of factorizations of each integer up to the desired point. For each integer prod, you need to count how many simple factorizations i*j there are with i <= m, j <= n. See the divisor functions.
You need to iterate prod until you reach the desired point, midpt = N*M / 2. Cumulatively subtract σ0(prod) from midpt until you reach 0. Note that once prod passes min(i, j), you need to start cropping the divisor count, due to running off the edge of the multiplication table.
Is that enough to get you started?
Code of third method from this(https://leetcode.com/articles/kth-smallest-number-in-multiplication-table/#) site solve the problem.
bool enough(int x, int m, int n, int k) {
int count = 0;
for (int i = 1; i <= m; i++) {
count += std::min(x / i, n);
}
return count >= k;
}
int findK(int m, int n, int k) {
int lo = 1, hi = m * n;
while (lo < hi) {
int mi = lo + (hi - lo) / 2;
if (!enough(mi, m, n, k)) lo = mi + 1;
else hi = mi;
}
return lo;
}

I don't understand the how prime numbers are calculated and modPow function is working in the following code

A Magic Fraction for N is one that has the following properties:
It is a proper fraction (The value is < 1)
It cannot be reduced further (The GCD of the numerator and the denominator is 1)
The product of the numerator and the denominator is factorial of N. i.e. if a/b is the fraction, then a*b = N!
Examples of Magic Fractions are:
1/2 [ gcd(1,2) = 1 and 1*2=2! ]
2/3 [ gcd(2,3) = 1 and 2*3=3! ]
3/8 [ gcd(3,8) = 1 and 3*8=4! ]
2/12 for example, is not a magic fraction, as even though 2*12=4!, gcd(2,12) != 1
And Magic fractions for number 3 are: 2/3 and 1/6 (since both of them satisfy the above criteria, are of the form a/b where a*b = 3!)
Now given a number N, you need to print the total number of magic fractions that exist, for all numbers between 1 and N (include magic fractions for N, too).
Can anybody tell me what is modPow function doing?
Refer the link to see the question, that will give an idea why this code.
using namespace std;
#define ll long long int
#define S(n) scanf("%lld", &n)
ll MOD = 1e18 + 7;
ll modPow(ll a, ll b)
{
ll res = 1;
a %= MOD;
for (; b; b >>= 1) {
if (b & 1)
res = res * a % MOD;
a = a * a % MOD;
}
return res;
}
int main()
{
ll i, j;
ll va = 1;
ll sum = 0;
ll prime[1000] = { 0 };
for (i = 2; i <= 500; i++) {
if (prime[i] == 0)
for (j = 2 * i; j <= 500; j += i)
prime[j] = 1;
}
ll val[600] = { 0 };
val[1] = 0;
val[2] = 1;
ll co = 0;
for (i = 3; i <= 500; i++) {
if (prime[i] == 0) {
co++;
}
ll t1 = modPow(2, co);
val[i] = t1 + val[i - 1];
val[i] %= MOD;
// cout << i << " " << val[i] << "\n";
}
ll n;
S(n);
cout << val[n] << "\n";
}

Calculate Huge Fibonacci number modulo M in C++

Problem statement : Given two integers n and m, output Fn mod m (that is, the remainder of Fn when divided by m).
Input Format. The input consists of two integers n and m given on the same line (separated by a space).
Constraints. 1 ≤ n ≤ 10^18, 2 ≤ m ≤ 10^5
Output Format. Output Fn mod m.
I tried the following program and it didn't work. The method pi is returning the right Pisano period though for any number as per http://webspace.ship.edu/msrenault/fibonacci/fiblist.htm
#include <iostream>
long long pi(long long m) {
long long result = 2;
for (long long fn2 = 1, fn1 = 2 % m, fn = 3 % m;
fn1 != 1 || fn != 1;
fn2 = fn1, fn1 = fn, fn = (fn1 + fn2) % m
) {
result++;
}
return result;
}
long long get_fibonaccihuge(long long n, long long m) {
long long periodlength = pi(m);
int patternRemainder = n % periodlength;
long long *sum = new long long[patternRemainder];
sum[0] = 0;
sum[1] = 1;
for (int i = 2; i <= patternRemainder; ++i)
{
sum[i] = sum[i - 1] + sum[i - 2];
}
return sum[patternRemainder] % m;
}
int main() {
long long n, m;
std::cin >> n >> m;
std::cout << get_fibonaccihuge(n, m) << '\n';
}
The exact program/logic is working well in python as expected. What's wrong withthis cpp program ? Is it the data types ?
Performing 10^18 additions isn't going to be very practical. Even on a teraflop computer, 10^6 seconds is still 277 hours.
But 10^18 ~= 2^59.8 so there'll be up to 60 halving steps.
Calculate (a,b) --> (a^2 + b^2, 2ab + b^2) to go from (n-1,n)th to (2n-1,2n)th consecutive Fibonacci number pairs in one step.
At each step perform the modulus calculation for each operation. You'll need to accommodate integers up to 3*1010 &leq; 235 in magnitude (i.e. up to 35 bits).
(cf. a related older answer of mine).
This was my solution for this problem, it works well and succeeded in the submission test ...
i used a simpler way to get the pisoano period ( pisano period is the main tricky part in this problem ) ... i wish to be helpful
#include <iostream>
using namespace std;
unsigned long long get_fibonacci_huge_naive(unsigned long long n, unsigned long long m)
{
if (n <= 1)
return n;
unsigned long long previous = 0;
unsigned long long current = 1;
for (unsigned long long i = 0; i < n - 1; ++i)
{
unsigned long long tmp_previous = previous;
previous = current;
current = tmp_previous + current;
}
return current % m;
}
long long get_pisano_period(long long m)
{
long long a = 0, b = 1, c = a + b;
for (int i = 0; i < m * m; i++)
{
c = (a + b) % m;
a = b;
b = c;
if (a == 0 && b == 1)
{
return i + 1;
}
}
}
unsigned long long get_fibonacci_huge_faster(unsigned long long n, unsigned long long m)
{
n = n % get_pisano_period(m);
unsigned long long F[n + 1] = {};
F[0] = 0;
F[-1] = 1;
for (int i = 1; i <= n; i++)
{
F[i] = F[i - 1] + F[i - 2];
F[i] = F[i] % m;
}
return F[n];
}
int main()
{
unsigned long long n, m;
std::cin >> n >> m;
std::cout << get_fibonacci_huge_faster(n, m) << '\n';
}

For loop divide numbers

I'm an amateur when it comes to C++ but I've already received a task which is over my knowledge.
Task is to enter numbers n,m. Programme must take it as an interval, in which it checks if there is any number which is a sum of numbers with the same exponent.
EDIT:(18.10.15)
Turns out I didn't understood my task correctly. Here it is:
"User enter two numbers. Programme takes it as the interval in which it checks all the numbers. If there's a number in interval which all digit's sum of SAME exponent is that number, then programme shows it."
For example, I enter 100 and 200. In this interval there's 153.
153 = 1^3 + 5^3 + 3^3 (1+125+27)
Programme shows 153.
cin >> n;
cin >> m;
for (int i=n; i<=m; i++)
{
for (int k=n; k<=i; k++)
{
a = n % 10; //for example, I enter 153, then a=3
f = n /= 10; //f=15
b = f % 10; //b=5
f = f /= 10; //f=1
c = f % 10; //c=1
f = f /= 10;
d = f % 10;
for (int j=1; j<=5; j++)
{
a = a * a;
b = b * b;
c = c * c;
d = d * d;
if (a + b + c + d == n)
{
cout << n << endl;
}
}
}
}
Any help will be appreciated.
Task is to enter numbers n,m. Programme must take it as an interval, in which it checks if there is any number which is a sum of numbers with the same exponent.
Assuming the range is given as [n, m), then here's your program:
return (n != m);
Any number can be seen as a sum of numbers with the same exponent. For example:
0 = 0 ^ 3 + 0 ^ 3 + 0 ^ 3
1 = 1 ^ 3 + 0 ^ 3
2 = 1 ^ 3 + 1 ^ 3
3 = 1 ^ 3 + 1 ^ 3 + 1 ^ 3
and so on. This is true even for negative numbers.
So in any non-empty range there exists at least 1 such number.
"All I know is how to get the programm to check each number separately"
"Programme must not use arrays."
for (int i = n; i <= m; i++) {
...
int x = (int)Math.log10(i);
int rest = i;
for (int p = x; p>=0; p--) {
int digit = rest / (int)Math.pow(10,p);
rest = i % (int)Math.pow(10,p);
//3802 = 3*10^3 + 8*10^2 + 0*10^1 + 2*10^0
}
}
...
Sorry, is Java no C++
Sorry that I answer so late and that I phrased my question poorly - English isn't my native language.
But turns out I didn't understood my task correctly. Here it is:
"User enter two numbers. Programme takes it as the interval in which it checks all the numbers. If there's a number in interval which all digit's sum of SAME exponent is that number, then programme shows it."
For example, I enter 100 and 200. In this interval there's 153.
153 = 1^3 + 5^3 + 3^3 (1+125+27)
Programme shows 153.
cin >> n;
cin >> m;
for (int i=n; i<=m; i++)
{
for (int k=n; k<=i; k++)
{
a = n % 10; //for example, I enter 153, then a=3
f = n /= 10; //f=15
b = f % 10; //b=5
f = f /= 10; //f=1
c = f % 10; //c=1
f = f /= 10;
d = f % 10;
for (int j=1; j<=5; j++)
{
a = a * a;
b = b * b;
c = c * c;
d = d * d;
if (a + b + c + d == n)
{
cout << n << endl;
}
}
}
}