//JavaClasses/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java //Mattrixwv // Created: 08-20-22 //Modified: 08-11-24 //This class generates triangular 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 triangular numbers, which implements the {@link Iterator} interface. * *

* Triangular numbers are figurate numbers that represent triangles. The n-th triangular number is given by * the formula: T(n) = n(n + 1) / 2. *

* *

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

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