Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*A “star number”, s, is a number defined by the formula: s = 6n(n-1) + 1 where n is the index
- *of the star number. Thus the star numbers are: 1, 13, 37, 73, 121, 181, 253, …
- *A “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n.
- *Thus the triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136,
- *153, 171, 190, 210, 231, 253, …
- *Write a Java application that produces a list of all the values of type int that are simultaneously
- *star numbers and triangle numbers. As part of this problem you must write and use the following functions:
- * An isStarNumber() routine which determines if the passed number is a star number or not.
- * A determineStarNumber() function which returns the star number of a passed index (i.e. value of n).
- */
- public class TriangularStars {
- public static int currentNumber = 0;
- public static int previousNumber = 0;
- public static void main(String[] args) {
- System.out.println("The following are numbers which are both triangle numbers and star numbers: ");
- int previousTriangleNumber=0;
- int currentTriangleNumber=0;
- int index=1;
- while (currentNumber>=previousNumber)
- {
- currentTriangleNumber = previousTriangleNumber + index;
- //System.out.println(currentTriangleNumber);
- previousNumber = currentNumber;
- if (isStarNumber(currentTriangleNumber))
- {
- System.out.print(currentTriangleNumber + ", ");
- }
- currentNumber = currentTriangleNumber;
- previousTriangleNumber = currentTriangleNumber;
- index++;
- }
- }
- public static boolean isStarNumber (int number)
- {
- boolean isStarNumber = false;
- int index = 0;
- int currentStarNumber = 0;
- int previousStarNumber = 0;
- while (!isStarNumber && currentStarNumber <= number )
- {
- previousStarNumber = currentStarNumber;
- currentStarNumber = determineStarNumber(index);
- //System.out.println(currentStarNumber + "; " + previousStarNumber);
- /* if (currentStarNumber < previousStarNumber)
- {
- isStarNumber = false;
- System.out.println(currentStarNumber);
- System.out.print("; " + index);
- }*/
- if (currentStarNumber == number)
- {
- isStarNumber = true;
- }
- else
- index += 1;
- }
- return (isStarNumber);
- }
- public static int determineStarNumber (int index)
- {
- /*int starNumberValue = 0;
- if (1 <= ((6*index)/Integer.MAX_VALUE) && 1 <= ((6*index) * (index-1)/Integer.MAX_VALUE))
- {
- starNumberValue = (6*index) * (index-1) + 1;
- }
- else
- starNumberValue = -1;
- */
- int starNumberValue = (6*index) * (index-1) + 1;
- return (starNumberValue);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement