减少if-else语句的数量和更简单的代码

时间:2017-10-17 22:42:19

标签: c# if-statement primes

不介意糟糕的编码,开始像1周前学习... 只用我知道的命令从ProjectEuler.net做了挑战,但是我已经结束了太多if-else语句我正在使用的公式...... 我如何使用相同的公式进行编码,但更干净/更优雅?

        double raiz, x;
        int y, tot1 = 0, tot2, z, raiz2;
        Console.WriteLine("Escreva o numero");
            x = int.Parse(Console.ReadLine());
            if (x == 2 || x == 3 || x == 5)
                Console.WriteLine("eh primo");
            else
                if (x % 2 == 0 || x < 7)

                Console.WriteLine("Numero {0} nao eh primo", x);
                else
                {
                    raiz = Math.Truncate(Math.Sqrt(x));
                    raiz2 = Convert.ToInt32(raiz);
                    z = Convert.ToInt32(x);
                    for (y = 3; y <= raiz2; y++)
                    {
                        tot1 = z / y;
                        tot2 = z % y;
                        if (tot2 == 0)
                        {
                            Console.WriteLine("{0} nao eh primo", x);
                            raiz2 = y;
                        }
                        else
                            if (y >= raiz2)
                            {
                                Console.WriteLine("{0} eh primo", x);
                                y+=raiz2;
                            }
                    }                    
                    if (y<=raiz2)
                        Console.WriteLine("{0} nao eh primo", x);
                    Console.ReadKey();

我正在使用此公式查找素数:

√PrimeNumber=SquareRoot

for (x = 3; x <= SquareRoot; x++)
if PrimeNumber % X = 0   
"not prime" 

else if 
 x == SquareRoot  
"prime"

1 个答案:

答案 0 :(得分:2)

不要为arrow-head anti-pattern而堕落。

我已将大部分代码作为函数multiple return statements提取出来。否则,我只做了很少的修改以表明我的观点。

static void Main(string[] args)
{
    double x;
    Console.WriteLine("Escreva o numero");
    x = int.Parse(Console.ReadLine());
    if(IsPrime(x))
        Console.WriteLine("eh primo", x);
    else
        Console.WriteLine("{0} nao eh primo", x);
    Console.ReadKey();
}

private static bool IsPrime(double x)
{
    double raiz;
    int y, tot1 = 0, tot2, z, raiz2;
    if (x == 2 || x == 3 || x == 5)
        return true;
    if (x % 2 == 0 || x < 7)
        return false;

    bool result = false;
    raiz = Math.Truncate(Math.Sqrt(x));
    raiz2 = Convert.ToInt32(raiz);
    z = Convert.ToInt32(x);
    for (y = 3; y <= raiz2; y++)
    {
        tot1 = z / y;
        tot2 = z % y;
        if (tot2 == 0)
        {
            result = false;//return
            raiz2 = y;
        }
        else
            if (y >= raiz2)
        {
            result = true;//return
            y += raiz2;
        }
    }
    if (y <= raiz2)
        return false;

    return result;            
}