一、水仙花数
链接:水仙花数
- 描述:
春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的:“水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153=1^ 3+5^ 3+3^3。- 现在要求输出所有在m和n范围内的水仙花数。 输入描述: 输入数据有多组,每组占一行,包括两个整数m和n(100 ≤ m ≤ n ≤999)。
- 输出描述:
对于每个测试实例,要求输出所有在给定范围内的水仙花数,就是说,输出的水仙花数必须大于等于m,并且小于等于n,如果有多个,则要求从小到大排列在一行内输出,之间用一个空格隔开;
如果给定的范围内不存在水仙花数,则输出no; 每个测试实例的输出占一行。
输入:
100 120
300 380
输出:
no
370 371
解题思路:
- 因为要求 m 和 n 范围内的水仙花数,所以可以使用 for 循环来判断 m~n 之间有多少个水仙花数。
- 想办法取出该数的每一位数,其次幂不需要考虑都为立方。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
while (num.hasNextInt()) {
int m = num.nextInt();//这里m在上n在下,n > m
int n = num.nextInt();
int flag = 0; //用于确认水仙花,1为水仙花数,0则不是。
//判断是否为水仙花数
for (int i = m ; i <= n; i++) {
int sum = 0;
int a = i;
if (i == (Math.pow(i/100, 3) + Math.pow(i%100/10, 3) + Math.pow(i%10, 3))){
System.out.print(i + " ");
flag = 1;
}
}
if (flag == 0) {
System.out.println("no");
}
}
}
}
i/100 取出的是百位数,i%100/10 取出的是十位数,i%10则是个位数。
二、变种水仙花
牛客网题目链接:变种水仙花
描述
变种水仙花数 - Lily Number:把任意的数字,从中间拆分成两个数字,比如1461
可以拆分成(1和461),(14和61),(146和1),如果所有拆分后的乘积之和等于自身,则是一个Lily Number。例如:
655 = 6 * 55 + 65 * 5
1461 = 1461 + 1461 + 146*1
求出 5位数中的所有 Lily Number。输出描述:
一行,5位数中的所有 Lily Number,每两个数之间间隔一个空格。
解题思路:
- 如12345:
求51234,45123,34512,23451后相加。
public class Main {
public static void main(String[] args) {
for (int i = 10000; i <= 99999; i++) {
int a = (i%10) * (i/10);
int b = (i%100) * (i/100);
int c = (i%1000) * (i/1000);
int d = (i%10000) * (i/10000);
if (a+b+c+d == i) {
System.out.print(i + " ");
}
}
}
}
三、求质数个数
牛客网题目链接:求质数个数
描述:
KiKi知道了什么是质数(只能被1和他自身整除的数),他现在想知道所有三位整数中,有多少个质数。
解题思路:
- 用该数从2开始求余数直到 该数 - 1,如果中途中求余为0,则不是质数
public class Main {
public static void main(String[] args) {
int i = 0;
int count = 0; //用于统计质数的个数
for (i = 100; i <= 999; i++) {
int j = 0;
//判断是不是质数
for (j = 2; j < i; j++) {
if (i % j == 0) { //不是质数判断
break;
}
}
if (i == j) { //是质数判断
count++;
}
}
System.out.println(count);
}
}