Cod sursa(job #2182071)

Utilizator cyg_SerbanBFlorin Gheorghe cyg_SerbanB Data 22 martie 2018 09:01:49
Problema Next Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.11 kb
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
long long int modulo(string s,long long int a)
{
    long long int res = 0;
    for(int i=0;i<s.length();i++)
         res=(res*10+(long long int)s[i]-'0')%a;
    return res;
}
string findSum(string str1, string str2)
{
    // Before proceeding further, make sure length
    // of str2 is larger.
    if (str1.length() > str2.length())
        swap(str1, str2);

    // Take an empty string for storing result
    string str = "";

    // Calculate lenght of both string
    int n1 = str1.length(), n2 = str2.length();

    // Reverse both of strings
    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());

    int carry = 0;
    for (int i=0; i<n1; i++)
    {
        // Do school mathematics, compute sum of
        // current digits and carry
        int sum = ((str1[i]-'0')+(str2[i]-'0')+carry);
        str.push_back(sum%10 + '0');

        // Calculate carry for next step
        carry = sum/10;
    }

    // Add remaining digits of larger number
    for (int i=n1; i<n2; i++)
    {
        int sum = ((str2[i]-'0')+carry);
        str.push_back(sum%10 + '0');
        carry = sum/10;
    }

    // Add remaining carry
    if (carry)
        str.push_back(carry+'0');

    // reverse resultant string
    reverse(str.begin(), str.end());

    return str;
}
int main()
{
    ifstream cin("next.in");
    ofstream cout("next.out");
    string n;
    long long int m,rest,leng;
    char aux;
    cin>>n>>m;
    rest=modulo(n,m);
    if(rest==0)
    {
        cout<<n;
        return 0;
    }
    else
    {
        rest=m-rest;
        string afis,restring;
        do
        {
            aux=rest%10+'0';
            restring.push_back(aux);
            rest/=10;
        }while(rest);
        leng=restring.size();
        for(int i=0;i<leng;++i)
        {
            aux=restring[leng-(i+1)];
            restring[leng-(i+1)]=restring[i];
            restring[i]=aux;
        }
        afis=findSum(n,restring);
        cout<<afis;
    }
    return 0;
}