C# 出于某种原因,我的代码似乎忽略了一个循环
我正试图解决ProjectEuler的第三个问题,但编译器似乎跳过了for循环,所以我的代码完全没有用处 注意:idea没有显示任何语法错误 代码如下:C# 出于某种原因,我的代码似乎忽略了一个循环,c#,for-loop,C#,For Loop,我正试图解决ProjectEuler的第三个问题,但编译器似乎跳过了for循环,所以我的代码完全没有用处 注意:idea没有显示任何语法错误 代码如下: class Program { static void Main(string[] args) { const long n = 600851475143; List<long> factors = new List<long>();
class Program
{
static void Main(string[] args)
{
const long n = 600851475143;
List<long> factors = new List<long>();
factors = getFactors(Math.Sqrt(n));
long max = 0;
for (int i = 0; i<factors.Count ;i++)//this loop in particular , it doesn't print the "testing.."
{
Console.WriteLine("test....");
if(isPrime(getFactors(factors[i])))
{
max = factors[i];
}
}
Console.ReadKey();
}
static List<long> getFactors(double number)
{
List<long> list = new List<long>();
for(int i = 2;i<=number;i++)
{
if(number%i ==0)
{
list.Add(i);
}
}
return list;
}
static bool isPrime(List<long> list)
{
if(list.Count == 2)
{
return true;
}
else
{
return false;
}
}
}
类程序
{
静态void Main(字符串[]参数)
{
常数长n=600851475143;
列表因子=新列表();
factors=getFactors(Math.Sqrt(n));
长最大值=0;
对于(int i=0;istatic List getFactors(双倍数字)
{
列表=新列表();
对于(int i=2;i当我运行代码时,我会在for循环之前打印出列表的长度。打印的值是0
。您的列表是空的,因此循环没有执行。您肯定会想看看如何使用调试器。在尝试诊断应用程序的行为为何与您的不同时,它是一个非常有用的工具预期。这是因为您选择的数字的平方根会产生一个带十进制值的双精度。用整数修改的非整数永远不会等于零。@Abion47-“never”被夸大了,但它会经常失败。而moded是模化的。除了@itsme86的建议之外,这里还有一些您需要注意的技巧ht发现有帮助。可以将Math.Floor()从循环中拉出。
static List<long> getFactors(double number)
{
List<long> list = new List<long>();
for (int i = 2; i <= number; i++)
{
if (Math.Floor(number % i) == 0)
{
list.Add(i);
}
}
return list;
}