水仙花数的优化解法

水仙花数的优化解法

水仙花数 Narcissistic number :指一个三位数其各位数字的立方和等于该数本身,延伸之后:一个N位数其各位数字的N次方和等于该数本身。



解法

对于三位的水仙花数,我们可以定义三个变量a,b,c,使其分别表示该数字的个十百位,再进行计算判断。

但是当拓展到N位是,我们再去定义N个变量表示每一位显然是不可能的,对此我们进行了while循环的优化。这也是最常见的优化。

'''
Description: 水仙花数的while循环,Python实现。单个数字的判断
Author: Alan
Date: 2021-06-10 19:25:15
LastEditTime: 2021-06-10 19:28:58
LastEditors: Alan
'''

num = int(input("请输入要判断的数字:"))
res, temp, length = 0, num, len(str(num))
while temp:
    res += (temp % 10)**length
    temp //= 10
print(f"The {num} is Daff_num!" if res ==
      num else f"The {num} isn`t Daff_num!")

水仙花数的优化解法_第1张图片



解法优化

  • 以上解法在单个数字的判断上,还是很快的;在判断九位数字以内的水仙花数的个数时,也可以很好的解决,但是当解决十位,十位以上的数字有多少个水仙花数的时候,就会显得很吃力。对此,我们应当继续优化算法,降低时间复杂度

  • 查阅资料之后,对于以上算法的优化,我们的着手点在于:乘方的计算上!对于以上算法,我们每分离出一个数字,都要进行一遍该数字的n次幂计算,但是该计算的时间复杂度并不是1,而是O(logN),所以我们的可以在此进行优化。

  • 首先定义一个数组,用于存放0 ~ 9 每个数字的 n次幂,当分离出数字之后,直接查找该数字的 n次幂,从而降低计算量,达到优化的目的。

/** 
* @Author Alan
* @Time 2021年5月31日 下午7:25:47 
* @Version 3.0
* 

Description:一次优化,while()循环;二次优化,引入数组! * 代码适用:输入一个数字N,求出N位的水仙花数。(N ≤ 9)

*/
import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int temp = 0; int[] arr_n = new int[10]; for(int i= 0; i < 10; i++) arr_n[i] = (int) Math.pow(i, n); int m = (int) Math.pow(10, n-1); int s = (int) Math.pow(10, n); for(int i = m ; i < s ;++i){ if(i % 100 == 0) continue; int temp1 = i,res = 0; while(temp1 > 0){ temp = temp1%10; res += arr_n[temp]; temp1 /= 10; } if(res == i) System.out.println(i); } scan.close(); } }

水仙花数的优化解法_第2张图片


# -*- codeing = utf-8 -*-
# @Time : 2021/6/10 19:53
# @Author : Alan
# @File : Daff_num.py
# @Software : PyCharm
# @Version : 3.0
# @Description :水仙花数的优化解法,Python实现。算法求解区间内的水仙花数
start = int(input("请输入区间左数字:"))
end = int(input("请输入区间的右数字:"))
arr_n = []
count = 0
temp1, temp2 = start, end
while temp1 < temp2:
    temp = []
    for j in range(10):
        temp.append(j ** (len(str(temp1))))
    temp1 *= 10
    arr_n.append(temp)
for num in range(start, end):
    temp, res = num, 0
    while temp:
        res += arr_n[len(str(num)) - len(str(start))][temp % 10]
        temp //= 10
    if res == num:
        count += 1
        print(f"{count}个: {num}")
print("水鲜花数的个数是:", count)

水仙花数的优化解法_第3张图片



结语

可能表述不清。

仅供参考,欢迎批评指正!

:2535865036

你可能感兴趣的:(习题记录,java,python,算法,python,java)