Saturday, May 21, 2016

SPOJ Problem CRZYSMKR

CRAZY SMOKER


Explanation:

A simple problem which requires li'l bit of modular arithmetics and we are done.
We just need to calculate the results of (34 ^ n) % 11 and (30 * n) % 11. Add 32 to it.

Once we have the result of above calculation, we need to find the minimum number to be added to the above result so that final result becomes equal to (0 % 11). We do it by subtracting it from 11 and taking a modulo 11. Taking modulo 11 helps for the case where n = 0.

Below is the code for reference.

Solution:

#include <iostream>
#include <cstdio>
using namespace std;

long long int mulMod(long long int a, long long int b, long long int c){
    // returns (a * b) % c.
    long long int x = 0, y = a % c;
    while (b) {
        if (b & 1)
            x = (x + y) % c;
        y = (y << 1) % c;
        b >>= 1;
    }
    return (x % c);
}

long long int modPower(long long int a, long long int b, long long int c){
    // returns (a ^ b) % c.
    long long int y = 1;
    while (b) {
        if (b & 1)
            // y = (y * a) % mod;
            y = mulMod(y, a, c);
        // a = (a * a) % mod;
        a = mulMod(a, a, c);
        b >>= 1;
    }
    return y;
}

long long int calculateCigarettes(long long int n){
    return (modPower(34, n, 11) + mulMod(30, n, 11) + 32) % 11;
}

int main() {
    int t;
    long long int n;
    scanf("%d", &t);
    while(t--){
        scanf("%lld", &n);
        printf("%lld\n", (11 - calculateCigarettes(n)) % 11);
    }
    return 0;
}

Any suggestions are welcome.

4 comments:

  1. i googled about (a*b)%c but couldn't understand this part.how the code of (a*b)%c parts works?plz give an example !!

    ReplyDelete
    Replies
    1. Will it be possible for you to elaborate lil more on what exactly you want me to explain.

      Delete
  2. explain Mulmod function in your code.that how multiply two number using bitwise operation that you used in Mulmod function.Thanks.

    ReplyDelete
    Replies
    1. Okay. Gotcha!
      Let's take an example and first try to multiply the numbers in base-10.

      45 * 13

      so, result for this will be,

      Product = 45 * 3 + 45 * 10 * 1 = 585.

      Similarly, when we try multiplying two numbers in binary (base-2), we do something like this.

      45 * 13
      = 101101 * 1101 (converting to binary).
      = 101101 * 1 + 101101 * 2 * 0 + 101101 * 4 * 1 + 101101 * 8 * 1

      And, we choose this method as this reduces the number of multiplication operations, and reduces the time complexity, as in base-10, we have to multiply the number by 10, but for binary (base-2), we simply need one bitwise shift operator.

      Hope the explanation helped. :)

      Delete

SPOJ Problem ONEZERO

Ones and zeros Explanation: A very good problem to practice BFS skills. I think that much hint is good to give the problem a shot. An...