天天看點

CodeForces 550C Divisibility by Eight(枚舉)

【題目連結】​​click here~~​​

【題目大意】

給一個不超過100位的數字,要求能否删掉幾位數,剩下的數能被8整除

【解題思路】:這裡有個性質:如果一個數後三位能被8整除,那麼這個數就能被8整除

證明:舉一個5位數的例子吧,

例如

_____  _____  __              __  __                __  ___

abcde=ab000+cde=1000×ab+cde=8×125×ab+cde

很明顯,8×125×ab一定是8或者125的倍數,是以當cde能被8或者125整除時,五位數abcde就能被8或者125整除。位數再多也是一樣的,主要是1000=125*8

那麼隻要枚舉後三位即可

#include <bits/stdc++.h>
using namespace std;
int main()
{
    char str[110];
    while(cin>>str)
    {
        bool ok=false;
        int len=strlen(str);
        for(int i=0; i<len; ++i)
        {
            if((str[i]-'0')%8==0)
            {
                puts("YES");
                cout<<(str[i]-'0')<<endl;
                return 0;
            }
        }
        for(int i=0; i<len; ++i)
        {
            for(int j=i+1; j<len; ++j)
            {
                if(((str[i]-'0')*10+(str[j]-'0'))%8==0)
                {
                    puts("YES");
                    cout<<((str[i]-'0')*10+(str[j]-'0'))<<endl;
                    return 0;
                }
            }
        }
        for(int i=0; i<len; ++i)
        {
            for(int j=i+1; j<len; ++j)
            {
                for(int k=j+1; k<len; ++k)
                {
                    if(((str[i]-'0')*100+(str[j]-'0')*10+str[k]-'0')%8==0)
                    {
                        puts("YES");
                        cout<<((str[i]-'0')*100+(str[j]-'0')*10+str[k]-'0')<<endl;
                        return 0;
                    }
                }
            }
        }
        puts("NO");
    }
}      

繼續閱讀