C # finding the largest prime number factor

I am new to programming and I am developing C # programming skills. My application is designed to find the largest simple number coefficient entered by the user. But my application does not return the correct answer, and I really do not know where the problem is. could you help me?

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;
        }
    }
}
+3
source share
5 answers

It will be much faster to remove small factors until the remainder is simple.

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

    return n;
}

For example, if n = 784, it does 9 modulo operations instead of a few hundred. Counting even with sqrt limit will still do 21 modulo ops only in maxfactor, and another dozen in primo.

New optimized version here

+13
Console.WriteLine("El maximo factor primo es: " + mfp);

Console.WriteLine("El maximo factor primo es: " + num);
+4

(! en), . n/2 sqrt (n) +1

+1

Catalin DICU , , , , . , maxfactor "en", , :

static private long maxfactor (long n)
{
    for (long k = n / 2; k > 1; k--)
    {
        if (n % k == 0 && primo(k))
        {
            return k;
        }
    }

    // no factors found
    return 1;
}

primo false, .

+1

f # :

let lpf n =
    let rec loop n = function        
        |k when k*k >= n -> n
        |k when n % k = 0I -> loop (n/k) k
        |k -> loop n (k+1I)
    loop n 2I
0

Source: https://habr.com/ru/post/1738902/


All Articles