mirror of
https://bitbucket.org/Mattrixwv/javaclasses.git
synced 2025-12-07 07:23:57 -05:00
Added number generators
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
//JavaClasses/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java
|
||||
//Mattrixwv
|
||||
// Created: 08-20-22
|
||||
//Modified: 08-20-22
|
||||
//This class generates triangular numbers
|
||||
/*
|
||||
Copyright (C) 2022 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv.generators;
|
||||
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
|
||||
public class TriangularNumberGenerator implements Iterator<Long>{
|
||||
private Long num;
|
||||
|
||||
public TriangularNumberGenerator(){
|
||||
num = 1L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext(){
|
||||
return (num * num) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long next(){
|
||||
Long newNum = ((num * num) + num) / 2;
|
||||
++num;
|
||||
if(num > 0){
|
||||
return newNum;
|
||||
}
|
||||
else{
|
||||
throw new NoSuchElementException("Number overflow");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isTriangular(Long x){
|
||||
Long n = Math.round((Math.sqrt(1 + (8 * x)) - 1) / 2);
|
||||
return (((n * n) + n) / 2) == x;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user