Created
December 8, 2015 21:34
-
-
Save rorhug/48941dc68917c8af3f19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class TriangularStars { | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
Scanner input = new Scanner( System.in ); | |
String inputString=""; | |
do { | |
System.out.print("How many star&triangle number do you want? (or 'quit')"); | |
input = new Scanner( System.in ); | |
if (input.hasNextInt()) | |
{ | |
int countRequired = input.nextInt(); | |
int countProduced = 0; | |
int triangle_number = 0; | |
for (int triangle_n = 1; countProduced < countRequired; triangle_n++) { | |
triangle_number += triangle_n; | |
if (isStarNumber(triangle_number)) { // if it's both triangle and star | |
System.out.println(triangle_number); // print it | |
countProduced++; // and increase count produced | |
} | |
} | |
} | |
else if (input.hasNext()) { | |
inputString = input.next(); | |
} | |
} while (!inputString.equalsIgnoreCase("QUIT")); | |
} | |
public static int determineStarNumber(int n) | |
{ | |
return 6*n*(n-1) + 1; | |
} | |
public static boolean isStarNumber(int number) | |
{ | |
// keep going while i is less than or equal number because | |
// we know there isn't a star number less than it's position | |
for (int i = 0; i <= number; i++) { | |
if (determineStarNumber(i) == number) { return true; } | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment