gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:57:47 25 4
gpt4 key购买 nike

这是我被分配的问题:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com