首页 > 代码库 > Divisibility by Eight

Divisibility by Eight

把当前数删除几位然后能够整除与8
那么可得知大于3位数的推断能否整除于八的条件是(n%1000)%8==0
能够得出我们的结论:仅仅须要枚举后三位后两位后一位就可以知道是否可整除于8

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char a[200];
int main() {
    //printf("%d\n",344%8);
    int ans = 0 ;
    int flag = 0;
    scanf("%s",a);
    int l = strlen(a);

    if(l>=3) {
        for(int i=0; i<l-2; ++i) {
            if(a[i]==‘0‘) continue;
            for(int j=i+1; j<l-1; ++j) {
                for(int k=j+1; k<l; ++k) {
                    ans = (a[i]-‘0‘)*100+(a[j]-‘0‘)*10+a[k]-‘0‘;
                    if(ans%8==0){

                        flag=1;
                        break;
                    }
                }
                if(flag) break;
            }
            if(flag)break;
        }
    }
   // printf(" %d %d\n",flag,ans);
    if(!flag&&l>=2) {
        for(int i=0; i<l-1; ++i) {
            if(a[i]==‘0‘) continue;
            for(int j=i+1; j<l; ++j) {
                ans = (a[i]-‘0‘)*10+(a[j]-‘0‘);
                if(ans%8==0) {
                    flag=1;
                    break;
                }
            }
            if(flag) break;
        }
    }
    if(!flag) {
        for(int i=0; i<l; ++i)
            if((a[i]-‘0‘)%8==0) {
                ans=a[i]-‘0‘;
                flag=1;
                break;
            }
    }

    if(!flag) {
        puts("NO");
    } else puts("YES"),printf("%d\n",ans);
}
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

Divisibility by Eight