1. 写⼀个函数add,接收两个整数作为参数,返回这两个整数的和
public class TestSum {
public static void main(String[] args) {
int sum = add(1,2);
System.out.println(sum);
}
public static int add(int num1,int num2) {
return num1 + num2;
}
}
2. 写⼀个函数,接收⼀个整数,输出这个整数的所有因⼦
public class TestReceive {
public static void main(String[] args) {
number(51);
}
public static int number(int num) {
if(num == 0) {
return 0;
} else {
System.out.println(1);
for(int i = 2; i <= num; i++) {
if(num % i == 0) {
System.out.println(i);
}
}
}
return 1;
}
}
3. 写⼀个函数,接收⼀个整数n,输出1+2+3+…+n 的和
import java.util.Scanner;
public class TestSum {
public static void main(String[] args) {
int num = number();
int result = numberSum(num);
System.out.println(result);
}
public static int number() {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个整数:");
return input.nextInt();
}
public static int numberSum(int num) {
if(num == 1) {
return 1;
} else {
return num + numberSum(num - 1);
}
}
}
4. 写⼀个函数,接收⼀个整数参数n,输出n 个HelloWorld
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
int num = number();
numberSum(num);
}
public static int number() {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个整数n:");
return input.nextInt();
}
public static int numberSum(int n) {
for(int i = 1;i <= n; i++) {
System.out.println("HelloWorld");
}
return 1;
}
}
5. 写⼀个函数,接收⼀个整数,输出这个整数是⼏位数
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
int num = number1();
number2(num);
}
public static int number1() {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个整数n:");
return input.nextInt();
}
public static int number2(int n) {
int count = 1;
while(n >= 10) {
count++;
n /= 10;
}
System.out.println(count);
return 1;
}
}
6. 求⼀个三位数,该三位数等与其每位数字的阶乘之和
public class TestSum1 {
public static void main(String[] args) {
int a, b, c, i;
for (i = 100 ; i <= 999; i++) {
a = i % 10;
b = i / 10 % 10;
c = i / 100;
if (i == factorial(a) + factorial(b) + factorial(c)) {
System.out.println("其三位数是:" + i);
}
}
}
public static int factorial(int num) {
int sum = 1;
for (int i = 1; i <= num; i++) {
sum *= i;
}
return sum;
}
}
7. 验证哥德巴赫猜想:任何⼀个⼤于6的偶数,都能分解成两个质数的和。要求输⼊⼀个整数,输出这个数能被分解成哪两个质数的和
import java.util.Scanner;
public class Test4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数:");
int n = sc.nextInt();
for(int i = 1; i <= n/2; i++) {
int j = n - i;
if(primeNumbers(i) && primeNumbers(j)) {
System.out.println(n + " = " + i + " + " + j);
}
}
}
public static boolean primeNumbers(int n) {
boolean falg = true;
if(n < 3) {
falg = n > 1;
}
for(int i = 2; i <= Math.sqrt(n); i++) {
if(n % i == 0) {
falg = false;
}
}
return falg;
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-3397.html