Rectangle Area and Perimeter
Problem
The length and width of a rectangle are whole numbers. Print its area and its perimeter separated by a space. For 3 and 4 the area is 12 and the perimeter is 14.
Constraints
- 1 <= length, width <= 10^5
Examples
Input
3 4
Output
12 14
Solutions
Both answers come from one-line formulas, so the code is short. We join the two numbers into one output line.
/*
* Problem : Rectangle.
* Input : Length and width.
* Output : Area and perimeter.
* Approach: Formulas.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(long a, long b) {
// Step 1: Area is length times width. Perimeter is twice the sum of the two sides.
long area = a * b;
long perimeter = 2 * (a + b);
return area + " " + perimeter;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
System.out.println(solve(a, b));
}
}
Hints (2)
- Why is the perimeter twice the sum?
- Which numbers can get big?