总目录
代码
// 判断传入的值是不是自幂数
final IntPredicate isSelfPower = v -> {
String str = String.valueOf(v);
int len = str.length();
int sum = Arrays.stream(str.split(""))
.mapToInt(e -> Double.valueOf(Math.pow(Integer.parseInt(e), len)).intValue()).sum();
return v == sum;
};
// 统计出指定范围内的全部自幂数
public void showSelfPower(int len) {
IntStream.rangeClosed(1, len).parallel().filter(isSelfPower).forEach(System.out::println);
}
// 统计全部的水仙花数
public void showNarcissistic() {
IntStream.rangeClosed(100, 999).parallel().filter(isSelfPower).forEach(System.out::println);
}
// 在指定上限与下限范围内查找自幂数
public void showSelfPower(int start, int end) {
IntStream.range(start, end).parallel().filter(isSelfPower).forEach(v -> System.out.printf("%d, ", v));
System.out.println();
}
// 统计一下在不同区间上查找自幂数所花费的时间
public void showSelfPowerCalculateTime() {
for (int i = 10; i <= 1_000_000_000; i = i * 10) {//
long startTime = System.nanoTime();
showSelfPower(i, i * 10);
long endTime = System.nanoTime();
System.out.printf("Start value: %,d, Time: %f\n", i, (endTime - startTime) / 1_000_000_000.0);
}
}
测试
class SelfPowerTest {
@Test
void showSelfPower() {
SelfPower selfPower = new SelfPower();
selfPower.showNacissistic();
System.out.println("*********");
selfPower.showSelfPower(100_000);
selfPower.showSelfPowerCalculateTime();
}
}
如果非要说,可以这样讲,一行代码搞定求解自幂数。而上面的代码,为了能复用isSelfPower,而分开来写。
// 统计时间内容显示
Start value: 10, Time: 0.016531
407, 370, 371, 153,
Start value: 100, Time: 0.006864
9474, 8208, 1634,
Start value: 1,000, Time: 0.033655
54748, 92727, 93084,
Start value: 10,000, Time: 0.110999
548834,
Start value: 100,000, Time: 0.559786
4210818, 1741725, 9800817, 9926315,
Start value: 1,000,000, Time: 1.737638
24678050, 24678051, 88593477,
Start value: 10,000,000, Time: 20.555410
146511208, 472335975, 534494836, 912985153,
Start value: 100,000,000, Time: 319.193531
这个代码无法统计出10亿到100亿的,因为Int最大值就20多亿,而10亿到100亿中间,只有一个40多亿的自幂数,唉,先不算了,如果真想算,就用long类型吧