public static void main(String[] args) {
int sum = 1;
for(int i = 1;i <= 9;i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
5. 百元买百鸡:公鸡5元一只,母鸡3块一只,小鸡一元3只。用100元买100只鸡,各买多少只。
穷举法 - 穷尽所有的可能性直到找到正确答案
public static void main(String[] args) {
int i,j,k; //公鸡,母鸡,小鸡的数量
//公鸡最多买20只,母鸡最多买33只,小鸡用剩下的钱来买
for(i = 0;i <= 20;i++) {
for(j = 0;j <= 33;j++){//for(k = 0;k <= 99;k += 3;)//对小鸡也做一次循环(做三次循环浪费cpu)
k = 100 - i - j;//小鸡的只数
if (5*i + 3*j + k/3 == 100 && k % 3 ==0) {
System.out.println("cock:" + i + "只,"+ "hen:" + j + "只," + "chicken:" + k + "只");
}
}
}
}
6. 练习:找出1~10000之间的完美数
完美数(例如:6 = 1 + 2 + 3)
public static void main(String[] args) {
for(int a = 2;a <= 10000;a++){
int sum = 1;
for(int i = 2;i <= Math.sqrt(a);i++){
if (a % i == 0) {
sum += i;
if (a / i != i) {
sum += a/i;
}
}
}
if (a == sum) {
System.out.println(a);
}
}
}
public static boolean isLeapYear(int year){
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
public static int daysOfMonth(int year,int month){
int days;
switch (month) {
case 2:
days = isLeapYear(year) ? 29 : 28;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
default:
days = 31;
}
return days;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入年月日:");
int year = input.nextInt();
int month = input.nextInt();
int day = input.nextInt();
int total = 0;
for(int i = 1;i < month;i++ ){
total += daysOfMonth(year, i);
}
total += day;
System.out.printf("%d年%d月%d日是这一年的第%d天",year,month,day,total);
input.close();
}