「蓝桥杯」数字整除

2022-07-31,,

数字整除

    • 题目
    • 分析
    • 代码

题目

定理:把一个至少两位的正整数的个位数字去掉,再从余下的数中减去个位数的5倍。当且仅当差是17的倍数时,原数也是17的倍数 。

例如,34是17的倍数,因为3-20=-17是17的倍数;201不是17的倍数,因为20-5=15不是17的倍数。输入一个正整数n,你的任务是判断它是否是17的倍数。

输入

输入文件最多包含10组测试数据,每个数据占一行,仅包含一个正整数n(1<=n<=10^100),表示待判断的正整数。n=0表示输入结束,你的程序不应当处理这一行。

输出

对于每组测试数据,输出一行,表示相应的n是否是17的倍数。1表示是,0表示否。

样例输入

34
201
2098765413
1717171717171717171717171717171717171717171717171718
0

样例输出

1
0
1
0

分析

在这道题中,输入的值范围为:1<=n<=10^100,所以long的范围也小了,这题得使用BigInteger

BigInteger:可以处理包含任意长度数字序列的数值的类

在这道题中使用到的BigInteger的方法:

  1. 将普通数值转换为大数值
    BigInteger a = BigInteger.valueOf(100);
  2. 两个数值的计算
    BigInteger add(BigInteger other); //加
    BigInteger subtract(BigInteger other); //差
    BigInteger multiply(BigInteger other); //乘
    BigInteger divide(BigInteger other); //除

这题的思路简单直接放上代码

代码

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static int index = 0;
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int index= 0;
        int a[] = new int[10];
        while (true){
            String num = sc.next();
            if(num.equals("0")){
                break;
            }
            BigInteger bi = new BigInteger(num);
            int ge=5*Integer.parseInt(num.substring(num.length()-1));
            BigInteger zhengshu = bi.divide(BigInteger.valueOf(10));
            if((zhengshu.subtract(BigInteger.valueOf(ge))).mod(BigInteger.valueOf(17)).equals(BigInteger.valueOf(0))){
                a[index] = 1;
            }
            else {
                a[index]=0;
            }
            index++;
        }
        for(int i=0;i<index;i++){
            System.out.println(a[i]);
        }
    }
}

本文地址:https://blog.csdn.net/weixin_43764030/article/details/107697166

《「蓝桥杯」数字整除.doc》

下载本文的Word格式文档,以方便收藏与打印。