C#,寻找一个数的最大质因数

标签 c#

我是编程新手,正在练习我的 C# 编程技能。我的应用程序旨在查找用户输入的数字的最大质因数。但是我的应用程序没有返回正确的答案,我真的不知道问题出在哪里。你能帮我么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Calcular máximo factor primo de n. De 60 es 5.");
            Console.Write("Escriba un numero: ");
            long num = Convert.ToInt64(Console.ReadLine());
            long mfp = maxfactor(num);
            Console.WriteLine("El maximo factor primo es: " + num);
            Console.Read();
        }
        static private long maxfactor (long n)
        {
            long m=1 ;
            bool en= false;
            for (long k = n / 2; !en && k > 1; k--)
            {
                if (n % k == 0 && primo(k))
                {
                    m = k;
                    en = true;
                }
            }
            return m;

        }
        static private bool primo(long x)
        {
            bool sp = true;
            for (long i = 2; i <= x / 2; i++)
            {
                if (x % i == 0)
                    sp = false;
            }
            return sp;
        }
    }
}

最佳答案

在留数为质数之前,去除小因子会快得多。

static private long maxfactor (long n)
{
    long k = 2;
    while (k * k <= n)
    {
        if (n % k == 0)
        {
            n /= k;
        }
        else
        {
            ++k;
        }
    }

    return n;
}

例如,如果 n = 784,这将执行 9 次模运算而不是数百次。即使使用 sqrt 限制进行倒计时,仍然会在 maxfactor 中进行 21 次模运算,在 primo 中进行另外一打。

新的更优化的版本here

关于C#,寻找一个数的最大质因数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2535251/

相关文章:

c# - 添加SqlDbType.Text参数时应该使用什么大小的值?

c# - 具有多个 AND 条件的 DataTable 选择实现

c# - 带有动态 where 子句的参数化查询

c# - C#套接字阻止行为

c# - Azure 服务总线重试策略不会改变行为

C#-Monogame.Forms : Question about getting mouse coordinates

c# - 如何使用 ASP.Net C# 更改 CKEditor 的输入语言

c# - 重点加强。我做对了吗?

c# - 尝试从控制台应用程序访问Azure存储并收到异常 "Configuration system failed to initialize"

c# - 什么时候真正需要 'Yield'?