尾数前移

尾数前移

问题描述

求一个自然数N,个位数是6,将6提到最前面所得数是N的4倍.

算法思路

  1. 令末位数t=6,其余的部分为n.
    举个例子就是 1236 => n=123,t=6 => nt
    按部分拆开是这个思路的关键
  2. n从1开始穷举,判断 4*nt =? tn

代码示例

Python

# 解题思路:
# 1236 => 6123 =? 4*1236
# t=6,n为除t的部分
# nt => n * 10 + t
# tn => t * math.pow(10,i) + n (i根据下面程序的循环来确定)

def fun(n):
    t = 6

    # 接下操作是为了提高t的位数
    # 例如 n=123,则t=60 => t=6000
    nn = n
    while nn >0:
        t *= 10
        nn /= 10
        nn = int(nn) # 这里注意了,除数不为0

    m = 10 * n + 6
    if t + n == 4 * m:
        print(m)


# 一个一个试探,1-1000,10000,100000
# 基本到10W都能出来答案
for x in range(1, 100000):
    fun(x)

Java


public class 尾数前移 {

    // 思路:4 * n * 10 + t =? t * Math.pow(10,i) + n
    // 4 * num1 =? num2
    static void fun(int n) {
        int t = 6;
        int num1 = n * 10 + t;

        int nn = n;
        while (nn > 0) {
            t *= 10;
            nn /= 10;
        }

        int num2 = t + n;
        if (4 * num1 == num2) {
            System.out.println(num1);
            return;
        }

    }

    public static void main(String[] args) {
        // n从1开始穷举
        for (int i = 1; i < 1000000; i++) {
            fun(i);
        }
    }
}


猜你喜欢

转载自www.cnblogs.com/Rowry/p/11789913.html