需要帮助来优化代码并使其没有错误 [英] need help to optimize the code and make it bug free

查看:138
本文介绍了需要帮助来优化代码并使其没有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请给我您的解决方案.我试图在Google上找到优化的答案,但我没有找到任何优化的代码.
Q:给定数素数的求和.例如,如果n = 18,答案将是2 + 3 = 5

以下是我的代码:

please give me your solution. i have tried to find the optimized answer on google but i dint find any optimized code.
Q:find sum of prime factors of given number. for example if n=18 answer would be 2+3=5

below is my code:

class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("Please provide Number : ");
            int num=Convert.ToInt32(Console.ReadLine());
            int sumRet = p.Prime_Fact(num);
            Console.WriteLine("Desired Result :{0} ",sumRet);

        }

        public int Prime_Fact(int n)
        {
            int originalNum=n;
            int sum=0;
            int primeLoop = 2;
            int check;
           g1: if (primeLoop < originalNum/2)
            {
                if (n % primeLoop == 0)
                {
                    sum = sum + primeLoop;
                    n = n / primeLoop;
                }
            g2: primeLoop++;
                if ((check = Prime_Fact(primeLoop)) == 0)
                {
                    goto g1;
                }
                else
                {
                    goto g2;
                }
            }


            return sum;
        }
    }



我需要对其进行优化.它也没有通过一些测试用例.测试用例没有给我.请给我您的建议.



i need to optimize it. it is not passing some test cases also. test cases are not given to me. Please give me your suggetions.

推荐答案

有很多方法可以做到这一点,例如,您可以让素数遍历所有从2到平方根的数字的"n",那么如果该数字除以n,则将其添加到另一个变量中,
另一种方法是使用橡皮泥筛子,然后在筛子中搜索2到"n"的平方根,如果数字除以"n",则将其添加到变量"sum"中这是最重要的
维基百科的链接
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes [
There are many ways to do that, for example you can get the prime factors looping through all the numbers from 2 to the square root of ''n'' then if that number divides n you add it to another variable,
another way to do it is using the sieve of erastotenes and then you search in the sieve from 2 to the square root of ''n'' and add it to a variable ''sum'' if the number divides ''n'' and it''s prime
a link from wikipedia
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes[^]


我们没有为您做作业.您必须编写代码.遇到困难时,您可以提出具体问题,以解决自己的问题.
We''re not doing your homework for you. YOU have to write the code. When you get stuck, you can ask specific questions about what you''re having a problem with.


这篇关于需要帮助来优化代码并使其没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆