/*分析: 目标:找出4位数的所有吸血鬼数字 1.什么是吸血鬼数字? 1)位数为偶数 2)可以分成2个数相乘,且2个数各包含乘积的一半位数,且2个数包含数字恰好为乘积所包含的数字 3)以两个0结尾的数字是不允许的 2.仔细观察描述-抽取逻辑 得到——相等逻辑1:结果相等 包含+位数——相等逻辑2:数字种类个数相同 */ //: control/E10_Vampire.java /****************** Exercise 10 ********************* * A vampire number has an even number of digits and * is formed by multiplying a pair of numbers containing * half the number of digits of the result. The digits * are taken from the original number in any order. * Pairs of trailing zeroes are not allowed. Examples * include: * 1260 = 21 * 60 * 1827 = 21 * 87 * 2187 = 27 * 81 * Write a program that finds all the 4-digit vampire * numbers. (Suggested by Dan Forhan.) ****************************************************/ public class E10_Vampire { /*这个解题思路:(苏格拉底反诘提问法)——学到了怎么分析问题 怎么存储数据?——前提是你得知道存储哪些数据?存储哪些数据由你的核心思路决定 问题端————>它的核心思路是啥? ——>核心问题:怎么输出哪个数 -通过满足一定条件-这个条件是一种逻辑式子 ——>怎样表达相等逻辑?——相等逻辑涉及什么数据? ——>一个是一对乘数+被乘数、一个是两部分的各位数字 用什么样的代码语句表达? 在必要条件的约束下,如果数字种类个数相同即可——通过计数器计数相等情况 ————>代码端 前两行是存储数据的代码块 对乘数的操作 */ public static void main(String[] args) { int[] startDigit = new int[4];//这个数组用来存放那一对数的各位数字 int[] productDigit = new int[4];//这个数组用来存放乘积的各位数字 for(int num1 = 10; num1 <= 99; num1++){//因为乘数最小为10,最大99,所以遍历[10,99] for(int num2 = num1; num2 <= 99; num2++) {//内层循环,当乘数1确定时,再遍历[10,99]——两者一共遍历[10,99]×[10,99] // Pete Hartley's theoretical result: // If x·y is a vampire number then // x·y == x+y (mod 9)//这里借用一个数学理论,如果是吸血鬼数,那么x·y 与 x+y对9的模相同(非充分条件,是必要条件) if((num1 * num2) % 9 != (num1 + num2) % 9) { continue;//如果模不同,直接跳过这次循环,提高效率了 int product = num1 * num2;//所有的数分成三部分考虑:乘数1,乘数2,乘积 startDigit[0] = num1 / 10; startDigit[1] = num1 % 10; startDigit[2] = num2 / 10; startDigit[3] = num2 % 10; productDigit[0] = product / 1000;//存储千位数字 productDigit[1] = (product % 1000) / 100;//存储百位 productDigit[2] = product % 1000 % 100 / 10;//存储十位数字 productDigit[3] = product % 1000 % 100 % 10;//存储个位数字 int count = 0; for(int x = 0; x < 4; x++){//两个数组存储的是乘数部分的数字和乘积部分的数字 for(int y = 0; y < 4; y++) { if(productDigit[x] == startDigit[y]) { count++; //productDigit[x] = -1; //startDigit[y] = -2; if(count == 4)//如果存在4中相等情况就符合 System.out.println(num1 + " * " + num2 + " : " + product); } } } } } } } }
吸血鬼数字问题
猜你喜欢
转载自www.cnblogs.com/DA-MO-WANG/p/10889681.html
今日推荐
周排行