A primary school math problem

topic

The four-digit abcd is A (that is, its thousands, hundreds, tens, and each are a, b, c, d), the smallest four digits composed of its four digits a, b, c, d Denoted as B.
If AB=999, how many such four-digit numbers are there?

C language solution:

#include <stdio.h>
int main()
{
    int a[4];
    int temp;  //插入排序辅助变量
    int j;
    int count=0;  //计数器
    for(int i =1000;i<10000;i++)
    {
        a[0]=i/1000;    //a
        a[1]=i/100%10;  //b
        a[2]=i/10%10;   //c
        a[3]=i%10;      //d
        for(int k=1;k<4;k++){  //插入排序
            temp=a[k];
            j=k;
            while(j>0 && a[j-1]>temp){
                a[j]=a[j-1];
                j--;
            }
            a[j]=temp;
        }
        if(a[0]==0){  //如果a[0]为0,把和左起第一个非0数交换 
            j=0;
            while(a[j]==0&&j<4){
                j++;
            }
            temp=a[0];
            a[0]=a[j];
            a[j]=temp;
        }
        if(i-(1000*a[0]+100*a[1]+10*a[2]+a[3]) == 999){  //A-B=999
            printf("%d ",i);  //A
            ++count;
            if(count%6==0)  //每6个换行 
                printf("\n") ;
            //printf("%d%d%d%d\n",a[0],a[1],a[2],a[3]);  //B
        }
    }
    printf("\n一共有%d个解\n",count);  //解个数
    return 0;
    //system("pause");
} 

The output result is:

 

[Answer Analysis]

AB=999 gets A=B+(1000-1). If the last number of B is not 0, then A is equal to B. Thousands digits+1 and ones digits-1. Conversely, B is equal to the thousand digits of A -1 and the ones digits +1. So B can be expressed as (a-1)bc(d+1).

Comparing B and A, the positions b and c are not exchanged, but a and d are exchanged. B can be expressed as dbca, so a=d+1. The value combinations of a and d are 2bc1-1bc2=999, 3bc2-2bc3=999,..., a total of eight groups.
For any of these combinations, there are six possibilities: a00d, a0dd, a0ad, adda, adad, aaad. Taking a=4 and d=3 as an example, there are six numbers 4003, 4033, 4043, 4333, 4343, and 4443. According to the principle of multiplication, there are a total of 8×6=48 types of four-digit numbers that meet the conditions.

Guess you like

Origin blog.csdn.net/weixin_42467709/article/details/83449593