题目描述
经过严密的计算,小赛买了一支股票,他知道从他买股票的那天开始,股票会有以下变化:第一天不变,以后涨一天,跌一天,涨两天,跌一天,涨三天,跌一天…依此类推。
为方便计算,假设每次涨和跌皆为1,股票初始单价也为1,请计算买股票的第n天每股股票值多少钱?
思路
数学推导
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import java.util.ArrayList; import java.util.Scanner;
public class Main {
public static void main(String[] args) { Main main = new Main(); Scanner scanner = new Scanner(System.in); main.res = new ArrayList<>(); while(scanner.hasNext()) { main.calculating(scanner.nextInt()); } main.res.forEach(Object -> System.out.println(Object)); } public ArrayList<Integer> res; public void calculating(int n) { int x = (int)(Math.sqrt(2*n) - 1); int j = x*(x+1) / 2; int delta = n - j; if(delta > x+1) { delta = delta - x -1; x = x+1; } if(delta == x+1) { delta = delta - 2; } int tmp; if(x >= 2) { tmp = 1+(x-1)*(x-2)/2; }else { tmp = 1; } res.add(tmp+delta); } }
|
考察点