c++multiplicationmodulo

Optimizing Modulo of Large Multiplication C++


I'm trying to make my program, which handles multiplications of large numbers with modulo, faster. This is my current code:

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    long multiply = 1;
    char x;
    while ( (x = getchar()) != '\n' )
    {
        multiply = (multiply*(x-64))%26;
    }
    if (multiply < 10)
        printf("0%d\n", multiply);
    else
        printf("%d\n", multiply);
    return 0;
}

Solution

  • (First of all, I get a warning because you use the symbol %d to print long, probably you can just use int and it won't make a difference since the maximum value is 26.)

    I think you could potentially improve the speed by using an unsigned integer type, since modulo is a bit simpler for unsigned integers. (It's hard to be sure just from looking at the generated assembly... )