[Daily Blue Bridge] 35, 2016 provincial competition Java group real question "Birthday Candle"

Hello, I am the little gray ape, a programmer who can write bugs!

Welcome everyone to pay attention to my column " Daily Blue Bridge ". The main function of this column is to share with you the real questions of the Blue Bridge Cup provincial competitions and finals in recent years, analyze the algorithm ideas, data structures and other content that exist in it, and help you learn To more knowledge and technology!

Title: Birthday Candle

A certain person will hold a birthday party every year since a certain year, and every time he blows out the same number of candles as his age.

Counting now, he has blown out 236 candles,

How old did he start his birthday party?

Please fill in the age when he started the birthday party

Note: What you submitted is an integer, please do not fill in any redundant content or descriptive text

Problem-solving ideas:

There are two ways to solve this question. One is the conventional way of thinking, that is, starting from a certain age and adding upwards, judging whether the number of candles will be equal to 236 after a certain year. If not, then re-judging from the next age , Until the year when the number of candles is exactly equal to 236 is obtained.

The second method is relatively simple, but the idea is not easy to think about. It is to use the arithmetic sequence to solve, add a candle every year, the first year is the prime minister, how many years it lasts is the number of phases, the tolerance is 1, the first n The sum of the years is 236, just enumerate the number of years, but pay attention to judging whether the obtained age is an integer, otherwise you will get a lot of results.

Answer source code:

Solution-conventional thinking

public class Year2016_Bt2 {

	public static void main(String[] args) {
		int ans = 1;
		int count = 0;
		for (int i = 1; i <=236; i++) {
			for (int j = i; j <= 236; j++) {
				count+=j;
				if (count==236) {
					ans=i;		
					break;
				}
				if (count>236) {
					break;
				}
			}
			if (count==236) {
				break;
			}
			count=0;
		}
		System.out.println(ans);
	}

}

Solving second arithmetic sequence

public class Year2016_Bt2_2 {

	public static void main(String[] args) {
		int ans = 0;
		//枚举已经过了的生日的年数n
		for (int n = 1; n < 100; n++) {
			//判断得到的年龄是不是整数
			if ((236-(n*(n-1)/2))%n==0) {
				int year = (236-(n*(n-1)/2))/n;
				System.out.println(year);
			}
		}

	}

}

 

Sample output:

Solution one output:

Solution two output:

 

There are deficiencies or improvements, and I hope that my friends will leave a message and learn together!

Interested friends can follow the column!

Little Gray Ape will accompany you to make progress together!

Guess you like

Origin blog.csdn.net/weixin_44985880/article/details/115006643