四叶玫瑰数是指四位数各位上的数字的四次方之和等于本身的数。
四位的四叶玫瑰数共有3个:1634,8208,9474;
// 求某个范围内值是否有四叶玫瑰数 一般是 1000~9999
function isFourLeafRose( min, max ){
const start = new Date(); // 记录一下运行耗时
const fourLeafRoseGroup = []; // 返回结果
// 判断参数类型是否为 Number
if( !Number(min)){
throw new Error('参数 min 不是 Number 类型!')
}
if( !Number(max)){
throw new Error('参数 max 不是 Number 类型!')
}
// 判断参数 Length 是否为 4 位数
if( min.toString().length !==4 ){
throw new Error('参数 min 不是 4 位数数值!')
}
if( max.toString().length !==4 ){
throw new Error('参数 max 不是 4 位数数值!')
}
// Math.pow(x,y) 返回 x 的 y 次幂。
console.log('Start Time:', new Date() - start );
for(let i=min; i<=max; i++ ){
const fourLeafRoseArray = i.toString().split('');
let powValue = 0;
for(let j=0; j<4; j++){
powValue += Math.pow(fourLeafRoseArray[j],4);
}
if(powValue===Number(i)){
fourLeafRoseGroup.push(i)
}
}
console.log('End Time:', new Date() - start );
return fourLeafRoseGroup;
}
网友评论