求余数

n个连续的某个正整数除以7的余数,例如9/7的余数是2.。。。。

输入:

输入数据有多行n,当n为0时结束

输出:

对于每行测试数据,计算余数,每个输出占一行

测试数据

输入

1

2

0

输出

2

1

分析:

int 型的数有范围,肯定不能用直接用一个特别大的数来求余数

像手算除法那样进行

还可以进行找规律。

方法①代码如下

#include<stdio.h>
int main()
{
    int n;
    while(1)
    {
        scanf("%d",&n);
        if(n==0)
        break;

        int k=n,res=0;
        while(k)
        {
            res=res*10+9;
            res=res%7;
            k--;
        }
        printf("%d\n",res);
    }
    return 0;
}

方法②通过规律

规律如下

 2, 1, 5, 3, 4, 0, 2, 1, 5, 3, 4, 0, 2, 1, 5

#include<stdio.h>
int main()
{
    int n;
    int a[6]={2,1,5,3,4,0};
    while(scanf("%d",&n))
    {
        if(n==0)
            break;
        int k=n%6;
        if(k==0)
            printf("%d\n",a[5]);
        else
            printf("%d\n",a[k-1]);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/acsuperman/article/details/80038279