gpt4 book ai didi

java - 为什么我得到奇怪的输出?

转载 作者:行者123 更新时间:2023-11-29 09:49:11 25 4
gpt4 key购买 nike

这个程序找到主要因素并像这样打印出来:factor (order) factor (order)

import java.util.Scanner;
import java.util.ArrayList;

public class Factorise2
{
public static ArrayList<Integer> get_prime_factors(int number)
{
//Get the absolute value so that the algorithm works for negative numbers
int absoluteNumber = Math.abs(number);
ArrayList<Integer> primefactors = new ArrayList<Integer>();
ArrayList<Integer> newprimes = new ArrayList<Integer>();
int b;
int c = (int)Math.sqrt(absoluteNumber);
//Get the square root so that we can break earlier if it's prime

for (int j = 2; j <= absoluteNumber;)
{
//Test for divisibility by j, and add to the list of prime factors if it's divisible.
if (absoluteNumber % j == 0)
{
primefactors.add(j);
absoluteNumber /= j;
c = (int)Math.sqrt(absoluteNumber);
}
else
{
for (int a = 0; a < newprimes.size();)
{
//Change j to the next prime
b = newprimes.get(a);
if (j % b == 0)
{
j++;
a = 0;
}
else
{
a++;
}
}
newprimes.add(j);
}
if (j > c)
{
primefactors.add(absoluteNumber);
break;
}
}
return primefactors;
}

public static void main(String[] args)
{
//Declare and initialise variables
int number;
int count = 1;
Scanner scan = new Scanner(System.in);
//Get a number to work with
System.out.println("Enter integer to analyse:");
number = scan.nextInt();
//Get the prime factors of the number
ArrayList<Integer> primefactors = get_prime_factors(number);
//Group the factors together and display them on the screen
System.out.print("Prime factors of " + number + " are ");
primefactors.add(0);
for (int a = 0; a < primefactors.size() - 1; a++)
{
if (primefactors.get(a) == primefactors.get(a+1))
{
count++;
}
else
{
System.out.print(primefactors.get(a) + " (" + count + ") ");
count = 1;
}
}
}
}

它在大多数情况下都有效,但是当我输入 131033809 时,我得到了一个奇怪的输出:

C:\Users\Eamon>java Factorise2
Enter integer to analyse:
4
Prime factors of 4 are 2 (2)
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
128
Prime factors of 128 are 2 (7)
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
9
Prime factors of 9 are 3 (2)
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
121
Prime factors of 121 are 11 (2)
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
131033809
Prime factors of 131033809 are 11447 (1) 11447 (1)

为什么不写

11447 (2)

最佳答案

在 Java 中,Integer 数据类型是一个对象。因此,== 操作只会在对象标识相同时返回 true:请注意,这与值是否实际上相等无关。你应该使用:

if (primefactors.get(a).equals(primefactors.get(a+1)))

关于java - 为什么我得到奇怪的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13434243/

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