//JavaClasses/src/main/java/mattrixwv/HexagonalNumberGenerator.java //Matthew Ellison // Created: 08-20-22 //Modified: 08-11-24 //This class generates hexagonal numbers /* Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ package com.mattrixwv.generators; import java.util.Iterator; import java.util.NoSuchElementException; /** * A generator for hexagonal numbers, which implements the {@link Iterator} interface. * *

* Hexagonal numbers are figurate numbers that represent hexagons. The n-th hexagonal number is given by * the formula: H(n) = 2n^2 - n. *

* *

* This generator allows iteration over hexagonal numbers starting from the first. *

*/ public class HexagonalNumberGenerator implements Iterator{ /** * The number to generate the next hexagonal number from. */ protected long num; /** * Constructs a new HexagonalNumberGenerator starting from the first hexagonal number. */ public HexagonalNumberGenerator(){ num = 1L; } /** * Checks if there is a next hexagonal number that can be generated without overflow. * * @return {@code true} if the next hexagonal number can be generated, {@code false} otherwise */ @Override public boolean hasNext(){ return (2 * num * num) > num; } /** * Returns the next hexagonal number. * * @return the next hexagonal number * @throws NoSuchElementException if the next hexagonal number would cause overflow */ @Override public Long next(){ //If the number will result in an overflow throw an exception if(!hasNext()){ throw new NoSuchElementException("Number overflow"); } //Generate and return the hexagonal number Long hexNum = ((2L * num * num) - num); ++num; return hexNum; } /** * Checks if a given number is a hexagonal number. * * @param x the number to check * @return {@code true} if the number is hexagonal, {@code false} otherwise */ public static boolean isHexagonal(Long x){ Long n = Math.round((Math.sqrt(1.0D + (8L * x)) + 1L) / 4L); return ((2L * n * n) - n) == x; } }