java - 在Java中查找既是三角形数又是星形数的数字

标签 java methods while-loop

这是我被分配的问题:

A so-called “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 first six (i.e. for n = 1, 2, 3, 4, 5 and 6) star numbers are: 1, 13, 37, 73, 121, 181

In contrast a so-called “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n. Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) triangle numbers are: 1, 3, 6, 10, 15, 21

Write a Java application that produces a list of all the values of type int that are both star number and triangle numbers.

When solving this problem you MUST write and use at least one function (such as isTriangeNumber() or isStarNumber() or determineTriangeNumber() or determineStarNumber()). Also you MUST only use the formulas provided here to solve the problem.

tl;dr:需要输出既是星数又是三角数的值。

不幸的是,即使我在 while 循环中加 1,我也只能在无限循环中得到输出值“1”的结果。

public class TriangularStars {
    public static void main(String[] args) {

    int n=1;            
    int starNumber = starNumber(n);
    int triangleNumber = triangleNumber(n);

    while ((starNumber<Integer.MAX_VALUE)&&(n<=Integer.MAX_VALUE))
    {
        if ((starNumber==triangleNumber)&& (starNumber<Integer.MAX_VALUE))
                {
                    System.out.println(starNumber);
                }
        n++;
    }
  }


public static int starNumber( int n)
{
    int starNumber;
    starNumber= (((6*n)*(n-1))+1);
    return starNumber;

}
public static int triangleNumber( int n)
{
    int triangleNumber;
    triangleNumber =+ n;
    return triangleNumber;
}

}

最佳答案

这是一个骨架。剩下的你自己完成:

问自己的问题:

  1. 如何生成三角形数?
  2. 我如何知道某物是否为星号?
  3. 为什么我只需要继续直到三角形为负?三角形怎么可能是负数?

祝你好运!

public class TriangularStars {
  private static final double ERROR = 1e-7;

  public static void main(String args[]) {
    int triangle = 0;
    for (int i = 0; triangle >= 0; i++) {
      triangle = determineTriangleNumber(i, triangle);
      if (isStarNumber(triangle)) {
        System.out.println(triangle);
      }
    }
  }

  public static boolean isStarNumber(int possibleStar) {
    double test = (possibleStar - 1) / 6.;
    int reduce = (int) (test + ERROR);
    if (Math.abs(test - reduce) > ERROR)
      return false;

    int sqrt = (int) (Math.sqrt(reduce) + ERROR);
    return reduce == sqrt * (sqrt + 1);
  }

  public static int determineTriangleNumber(int i, int previous) {
    return previous + i;
  }
}

输出:

1
253
49141
9533161
1849384153

关于java - 在Java中查找既是三角形数又是星形数的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13692327/

相关文章:

java - 如何将下载的图像从一个 Activity 传递到下一个 Activity ?

java - Spring Security 拒绝访问/actor/health

java - 如何使带有调度程序(Quartz)的应用程序可手动测试?

java - 如何旋转SeekBar上的TextView?

java - 在每个创建的对象上调用一个方法

c - 如何使用 C 中的 for 循环打印答案序列?

c# - 多个 Controller 之间的通用方法

java - 不使用方法的返回值,是不是设计不好?

python - 在 While 循环中访问全局 VAR 时出现问题

java - while 循环和队列的奇怪 java 行为