首页 > 代码库 > 问题6-10
问题6-10
6,求最大公约数和最小公倍数
import java.util.Scanner;
public class HCFandLCM {
public static void main(String[] args) {
int a, b, m;
Scanner scanner = new Scanner(System.in);
System.out.print("Please input a int number: ");
a = scanner.nextInt();
System.out.print("Please input a int number again: ");
b = scanner.nextInt();
HCF hcf = new HCF();
m = hcf.DE(a, b);
int n = a * b / m;
System.out.println("HCF IS:" + m);
System.out.println("LCM IS:" + n);
}
}
//求最大公约数
class HCF {
public int DE(int x, int y) {
int t;
if (x < y) {
t = x;
x = y;
y = t;
}
while (y != 0) {
if (x == y)
return x;
else {
int k = x % y;
x = y;
y = k;
}
}
return x;
}
}
7,求不同字符的个数:
import java.util.Scanner;
public class CountEnglishcharSpaceNumberOther {
public static void main(String[] args) {
int abcCount = 0;
int spaceCount = 0;
int numCount = 0;
int otherCount = 0;
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
// Converts this string to a new character array.
char[] ch = string.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (Character.isLetter(ch[i])) {
abcCount++;
} else if (Character.isDigit(ch[i])) {
numCount++;
} else if (Character.isSpaceChar(ch[i])) {
spaceCount++;
} else {
otherCount++;
}
}
System.out.println("THe number of abc: " + abcCount);
System.out.println("The number of nubmer: " + numCount);
System.out.println("The number of space: " + spaceCount);
System.out.println("Ther number of others: " + otherCount);
}
}
8,n个a+aa+……aaaa相加
import java.util.Scanner;
public class aaa {
public static void main(String[] args) {
long a, b = 0, sum = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Please input the value of a: ");
a = scanner.nextInt();
System.out.print("Please input the value of n: ");
int n = scanner.nextInt();
int i = 0;
while (i < n) {
b = b + a;
sum = sum + b;
a = a * 10;
++i;
}
System.out.println(sum);
}
}
9,求1000内的完数:
public class PerfectNum {
public static void main(String[] args) {
System.out.println("The perfect number between 1 and 1000 is :");
for (int i = 1; i < 1000; i++) {
int t = 0;
for (int j = 1; j <= i / 2; j++) {
if (i % j == 0) {
t = t + j;
}
}
if (t == i) {
System.out.println(i + " ");
}
}
}
}
10,落球第十次的路程和高度:
public class Ball {
public static void main(String[] args) {
double h = 100, s = 100;
for (int i = 1; i < 10; i++) {
s = s + h;
h = h / 2;
}
System.out.println("The path :" + s);
System.out.println("The High :" + h / 2);
}
}
问题6-10