Line of Best Fit
InterviewTime limit1sMemory limit128 MB
Given n points in the plane, compute the slope and intercept of the least squares regression line and print each rounded to three decimals.
- Level
Easy3 of 10
- Topics
- Math, Implementation, Prefix sum, Array
- Solved
- No attempts yet
Problem
Finding a line that best fits a set of data points in the plane is one of the fundamental problems in statistics and numerical analysis.
You are given a set of points in the plane, . For a line defined by the linear equation , the error of with respect to is defined as the sum of the squared vertical distances from the points of to the line:
The least squares method finds the line that minimizes this error. Write a program that, for a given set of points , computes the coefficients and of the line that minimizes the error.

Figure 1. An example of a set of points and its line of best fit.
Input
The first line contains the number of points (). Each of the next lines contains two integers and , the coordinates of a point, separated by a space (, ). It is guaranteed that the -coordinates are not all identical, so the line of best fit is uniquely determined.
Output
Print the value of on the first line and the value of on the second line. Both values must be rounded to three decimal places.