我正在尝试编写能够计算出素数的代码,但它认为没有什么是素数

时间:2017-02-04 03:25:26

标签: c# primes

所以我正在尝试找出素数,但我的程序认为一切都不是素数。有谁知道为什么? 编辑我想我应该详细阐述我想要完成的事情,我有三个变量,两个女巫它们在一起增加,如果问题是否大于C,如果这是情况它会把它写成素数(我已经看到了一些错误,我正在修理它)并且如果在某个时间点A次B等于C(C是我们试图找出的数字是素数还是没有)它将被写为素数

namespace ConsoleApplication3
{
    class Program
    {
        const string fileName = "NotPrime.txt";
        const string filnamePrime = "Prime.txt";
        static void Main(string[] args)
        {
            var c = 2;
            var a = 1;
            var b = 1;
            while (true)
            {
                if (a * b == 1)
                {
                    a = a + 1;
                }

                if ((a * b == c) && (c != 1))
                {
                    Console.WriteLine("{0} is not prime.", c);
                    using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
                    {
                        writer.Write(string.Format("{0}\r\n", c));
                    }
                    a = a = 1;
                    b = b = 1;
                    c = c + 1;
                }

                if ((a * b != c) && (c * b > c))
                {
                    Console.WriteLine("{0} is prime.", c);
                    using (BinaryWriter writesr = new BinaryWriter(File.Open(filnamePrime, FileMode.Create)))
                    {
                        writesr.Write(string.Format("{0}\r\n", c));
                    }
                    a = a = 1;
                    b = b = 1;
                    c = c + 1;
                }

                if (a * b < c)
                {
                    b = b + 1;
                    a = a = 1; // This is causing everything to mess up here but I know it will be nessesary once I figure out how to fix this current error.
                }
                Thread.Sleep(1000);

            }
        }
    }
}

1 个答案:

答案 0 :(得分:-2)

我认为您需要将单&更改为&&。单个&是一个按位和运算符,它具有比大多数其他运算符更高的运算顺序。这意味着它发生在==!=发生之前。你可能还想在你的表达式周围加上括号&#34; anding&#34;一起。这样就不会混淆你的意图。

相关问题