文章目录
一、水仙花数
链接:水仙花数
解题思路:
- 因为要求 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则是个位数。
二、变种水仙花
牛客网题目链接:变种水仙花
解题思路:
- 如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 + " ");
}
}
}
}
三、求质数个数
牛客网题目链接:求质数个数
解题思路:
- 用该数从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);
}
}