# Hogben Numbers in Java

In this section, we will learn what is Hogben number and also create Java programs to that calculates the Hogben number. The Hogben number program is frequently asked in Java coding interviews and academics.

## Hogben Number

The Hogben numbers are the numbers that are recursively defined as:

H(n) = H(n - 1) + 2 * (n - 1), where n >= 1 and H(0) = 1.

Thus,

H(1) = H(1 - 1) + 2 * (1 - 1) = H(0) + 2 * 0 = 1 + 0 = 1

H(2) = H(2 - 1) + 2 * (2 - 1) = H(1) + 2 * 1 = 1 + 2 = 3

H(3) = H(3 - 1) + 2 * (3 - 1) = H(2) + 2 * 2 = 3 + 4 = 7

H(4) = H(4 - 1) + 2 * (4 - 1) = H(3) + 2 * 3 = 7 + 6 = 13

H(5) = H(5 - 1) + 2 * (5 - 1) = H(4) + 2 * 4 = 13 + 8 = 21

Let's see the different approaches to find the Hogben numbers.

## Approach: Recursive

Let's see the recursive approach to find the first 10 Hogben numbers.

FileName: HogbenNum.java

Output:

```The first 10 Hogben numbers are:
1 3 7 13 21 31 43 57 73 91
```

Complexity Analysis: The time complexity of the program is O(n), where n is the nth number. The space complexity of the program is constant, i.e., O(1).

## Approach: Iterative

Let's see the iterative approach to find the first 10 Hogben numbers.

FileName: HogbenNum1.java

Output:

```The first 10 Hogben numbers are:
1 3 7 13 21 31 43 57 73 91
```

Complexity Analysis: The time complexity of the program is O(1). The space complexity of the program is constant, i.e., O(n), where n is the total number of Hogben numbers to be computed.

The current Hogben number is only dependent on the value of the last computed Hogben number. Therefore, instead of array, we can only use a variable to compute the Hogben numbers. See the following program.

FileName: HogbenNum2.java

Output:

```The first 10 Hogben numbers are:
1 3 7 13 21 31 43 57 73 91
```

Complexity Analysis: The time, as well as the space complexity of the program, is O(1).

## Approach: Using Mathematical Formula

The mathematical formula for computing the Hogben numbers are:

H(n) = n2 - n + 1, where n >= 1

Thus,

H(1) = 12 - 1 + 1 = 1 - 1 + 1 = 1

H(2) = 22 - 2 + 1 = 4 - 2 + 1 = 3

H(3) = 32 - 3 + 1 = 9 - 3 + 1 = 7

H(4) = 42- 4 + 1 = 16 - 4 + 1 = 13

H(5) = 52 - 5 + 1 = 25 - 5 + 1 = 21

Implementation

The following program uses the mentioned mathematical formula.

FileName: HogbenNum3.java

Output:

```The first 10 Hogben numbers are:
1 3 7 13 21 31 43 57 73 91
```

Complexity Analysis: The time, as well as the space complexity of the program, is O(1).

## Help Others, Please Share   