现在我正在尝试在解决这个欧拉项目问题3时有点创意,但程序正在进入一个infinte循环。我想我已经正确使用了ArrayList,但我忘记了一些事情。
class LargestPrimeFactor
{
public boolean prime(long n)
{
for(int i=1;i<=n-1;i++)
{
if(n%i==0)
return false;
}
return true;
}
public ArrayList primeFactors(long n)
{
ArrayList<Integer> primeFactors=new ArrayList<Integer>();
int i=2;
while(n!=1)
{
if((n%i==0)&(prime(i)))
{
primeFactors.add(i);
n/=i;
}
i++;
}
return primeFactors;
}
public int maxPrimeFactors(ArrayList<Integer> primeFactors)
{
int max=primeFactors.get(0);
for(int i=0;i<primeFactors.size();i++)
{
if(primeFactors.get(i)>max)
{
max=primeFactors.get(i);
}
}
return max;
}
}
class DemoLargestPrimeFactor
{
public static void main(String args[])
{
LargestPrimeFactor x=new LargestPrimeFactor();
ArrayList<Integer> list=new ArrayList<Integer>();
try
{
File file=new File("D:/JavaInEclipse/EulerProjects/src/Numbers.txt");
BufferedReader br=new BufferedReader(new FileReader(file));
String line="";
int n;
while((line=br.readLine())!=null)
{
n=Integer.parseInt(line);
list=x.primeFactors(n);
System.out.println("Max Prime Factor for " + n + " is =" + x.maxPrimeFactors(list));
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("File not found !!!");
}
}
}
答案 0 :(得分:1)
此外,您可能希望在此更改if条件。
if((n%i==0)&(prime(i))) // it should be && and not &