问题
生日蜡烛
某君从某年开始每年都举办一次生日party,并且每次都要吹熄与年龄相同根数的蜡烛。 现在算起来,他一吹熄了236根蜡烛。
请问,他从多少岁开始过生日party的?
解题
/**
* 生日蜡烛
*
* 某君从某年开始每年都举办一次生日party,并且每次都要吹熄与年龄相同根数的蜡烛。 现在算起来,他一吹熄了236根蜡烛。
* 请问,他从多少岁开始过生日party的?
*
* candleNumber 已经吹掉的蜡烛数
* lifeTopNumber 大概的寿命上限单位 年
*/
public static void countBirthDayPartyStartAge(int candleNumber, int lifeTopNumber){
if (candleNumber < 0 || lifeTopNumber < 0){
System.out.println("入参不能小于0");
return;
}
int sum = 0;
for (int age = 1; age <= lifeTopNumber; age++){
// 当前年龄不满足累加则继续下一个年龄 从1开始累加
sum = 0;
for (int currentAge = age; currentAge < lifeTopNumber; currentAge++){
// 从当前岁开始累加1 不是 从 2开始累加
sum += currentAge;
if (sum == candleNumber){
System.out.println(" start at age: " + age + " currentAge:" + currentAge);
return;
}else if (sum > candleNumber){
// 当前年龄任意累加不能满足条件 执行下一次循环
break;
}
}
}
}