C# 中的质因数

发布于 2024-11-04 11:25:28 字数 545 浏览 9 评论 0原文

我想用 C# 2005 创建一个程序来计算给定输入的素因数。我想使用基本和最简单的东西,不需要为其创建方法,也不需要数组等,只是简单的模数。有没有任何代码可以满足我的愿望?

这是查找简单因子的代码,我需要修改此代码来计算素因子

class Program
{
    static void Main(string[] args)
    {
        int a, b;
        Console.WriteLine("Please enter your integer: ");
        a = int.Parse(Console.ReadLine());
        for (b = 1; b <= a; b++)
        {
            if (a % b == 0)
            {
                Console.WriteLine(b + " is a factor of " + a);
            }
        }
        Console.ReadLine();



    }
}

I want to create a program in C# 2005 which calculates prime factors of a given input. i want to use the basic and simplest things, no need to create a method for it nor array things etc. just simple modulus. is there any code which fulfills what i desire?

here is the code for finding simple factors, i need this code to be modified to calculate prime factors

class Program
{
    static void Main(string[] args)
    {
        int a, b;
        Console.WriteLine("Please enter your integer: ");
        a = int.Parse(Console.ReadLine());
        for (b = 1; b <= a; b++)
        {
            if (a % b == 0)
            {
                Console.WriteLine(b + " is a factor of " + a);
            }
        }
        Console.ReadLine();



    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

摇划花蜜的午后 2024-11-11 11:25:28
int a, b;
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());

for (b = 2; a > 1; b++)
    if (a % b == 0)
    {
        int x = 0;
        while (a % b == 0)
        {
            a /= b;
            x++;
        }
        Console.WriteLine($"{b} is a prime factor {x} times!");
    }
Console.WriteLine("Th-Th-Th-Th-Th-... That's all, folks!");

在我的机器上运行!

int a, b;
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());

for (b = 2; a > 1; b++)
    if (a % b == 0)
    {
        int x = 0;
        while (a % b == 0)
        {
            a /= b;
            x++;
        }
        Console.WriteLine(
quot;{b} is a prime factor {x} times!");
    }
Console.WriteLine("Th-Th-Th-Th-Th-... That's all, folks!");

Works on my machine!

跨年 2024-11-11 11:25:28
public static List<int> Generate(int number)
{
    var primes = new List<int>();

    for (int div = 2; div <= number; div++)
        while (number % div == 0)
        {
            primes.Add(div);
            number = number / div;
        }
    
    return primes;
}

如果您想了解开发步骤,可以在此处观看视频< /a>.

public static List<int> Generate(int number)
{
    var primes = new List<int>();

    for (int div = 2; div <= number; div++)
        while (number % div == 0)
        {
            primes.Add(div);
            number = number / div;
        }
    
    return primes;
}

If you want to learn steps of development you can watch video here.

合约呢 2024-11-11 11:25:28

您可以做得更好,因为除数永远不会大于数字的平方根。

 for(int div = 2; div <= Math.Sqrt(number); div++)

You can go one better as the divisor can never be larger than the square root of the number.

 for(int div = 2; div <= Math.Sqrt(number); div++)
豆芽 2024-11-11 11:25:28

尝试这段代码(我在此代码中合并了各种解决方案)。虽然,插值不是在 2005 年(我认为是这样......)

所以,无论如何,试试这个:

// C# Program to print all prime factors 
using System; 

namespace prime
{
    public class Prime
    { 

        public static void PrimeFactors(int n)
        {
            Console.Write($"Prime Factors of {n} are:  ");

            // Prints all the numbers of 2  
            while (n % 2 == 0)
            {
                Console.Write("2 ");
                n /= 2;
            }

            // As no 2 can be further divided, this probably means that n
            // is now an odd number
            for(int i = 3; i <= Math.Sqrt(n); i += 2)
            {
                while (n % i == 0)
                {
                    Console.Write($"{i} ");
                    n /= i;
                }
            }

            // This is for case if n is greater than 2
            if (n > 2)
            {
                Console.Write($"{n} ");
            }

        }

        // Prompts user to give Input to number and passes it on 
        // the PrimeFactors function after checking its format
        public static void RunPrimeFactors()
        {
            Console.Write("Enter a number: ");
            if (int.TryParse(Console.ReadLine(), out int n))
            {
                PrimeFactors(n);
            }
            else
            {
                Console.WriteLine("You entered the wrong format");
            }

        }
        // Driver Code 
        public static void Main()
        {
            RunPrimeFactors();
        }

    }
}

Try this code (I incorporated various solutions in this code). Although, interpolation is not in 2005 (I think so....)

So, anyways, try this:

// C# Program to print all prime factors 
using System; 

namespace prime
{
    public class Prime
    { 

        public static void PrimeFactors(int n)
        {
            Console.Write($"Prime Factors of {n} are:  ");

            // Prints all the numbers of 2  
            while (n % 2 == 0)
            {
                Console.Write("2 ");
                n /= 2;
            }

            // As no 2 can be further divided, this probably means that n
            // is now an odd number
            for(int i = 3; i <= Math.Sqrt(n); i += 2)
            {
                while (n % i == 0)
                {
                    Console.Write($"{i} ");
                    n /= i;
                }
            }

            // This is for case if n is greater than 2
            if (n > 2)
            {
                Console.Write($"{n} ");
            }

        }

        // Prompts user to give Input to number and passes it on 
        // the PrimeFactors function after checking its format
        public static void RunPrimeFactors()
        {
            Console.Write("Enter a number: ");
            if (int.TryParse(Console.ReadLine(), out int n))
            {
                PrimeFactors(n);
            }
            else
            {
                Console.WriteLine("You entered the wrong format");
            }

        }
        // Driver Code 
        public static void Main()
        {
            RunPrimeFactors();
        }

    }
}
北座城市 2024-11-11 11:25:28

最有效的方法是使用轮分解的优化实现。下面的示例演示了 2, 3, 5 轮,只需考虑 (30k ± {1, 7, 11, 13}) 形式的因素。

public static IEnumerable<T> EnumeratePrimeFactors<T>(this T value) where T : IBinaryInteger<T>, IUnsignedNumber<T> {
    if (BinaryIntegerConstants<T>.Four > value) { yield break; }
    if (BinaryIntegerConstants<T>.Five == value) { yield break; }
    if (BinaryIntegerConstants<T>.Seven == value) { yield break; }
    if (BinaryIntegerConstants<T>.Eleven == value) { yield break; }
    if (BinaryIntegerConstants<T>.Thirteen == value) { yield break; }

    var index = value;

    while (T.Zero == (index & T.One)/* enumerate factors of 2 */) {
        yield return BinaryIntegerConstants<T>.Two;

        index >>= 1;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Three)) { // enumerate factors of 3
        yield return BinaryIntegerConstants<T>.Three;

        index /= BinaryIntegerConstants<T>.Three;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Five)/* enumerate factors of 5 */) {
        yield return BinaryIntegerConstants<T>.Five;

        index /= BinaryIntegerConstants<T>.Five;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Seven)/* enumerate factors of 7 */) {
        yield return BinaryIntegerConstants<T>.Seven;

        index /= BinaryIntegerConstants<T>.Seven;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Eleven)/* enumerate factors of 11 */) {
        yield return BinaryIntegerConstants<T>.Eleven;

        index /= BinaryIntegerConstants<T>.Eleven;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Thirteen)/* enumerate factors of 13 */) {
        yield return BinaryIntegerConstants<T>.Thirteen;

        index /= BinaryIntegerConstants<T>.Thirteen;
    }

    var factor = BinaryIntegerConstants<T>.Seventeen;
    var limit = index.SquareRoot();

    if (factor <= limit) {
        do {
            while (T.Zero == (index % factor)/* enumerate factors of (30k - 13) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Two;

            while (T.Zero == (index % factor)/* enumerate factors of (30k - 11) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Four;

            while (T.Zero == (index % factor)/* enumerate factors of (30k - 7) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Six;

            while (T.Zero == (index % factor)/* enumerate factors of (30k - 1) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Two;

            while (T.Zero == (index % factor)/* enumerate factors of (30k + 1) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Six;

            while (T.Zero == (index % factor)/* enumerate factors of (30k + 7) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Four;

            while (T.Zero == (index % factor)/* enumerate factors of (30k + 11) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Two;

            while (T.Zero == (index % factor)/* enumerate factors of (30k + 13) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Four;
            limit = index.SquareRoot();
        } while (factor <= limit);
    }

    if ((index != T.One) && (index != value)) {
        yield return index;
    }
}

The most efficient way is to use an optimized implementation of wheel factorization. Here is an example that demonstrates a 2, 3, 5 wheel that only needs to consider factors of the form (30k ± {1, 7, 11, 13}).

public static IEnumerable<T> EnumeratePrimeFactors<T>(this T value) where T : IBinaryInteger<T>, IUnsignedNumber<T> {
    if (BinaryIntegerConstants<T>.Four > value) { yield break; }
    if (BinaryIntegerConstants<T>.Five == value) { yield break; }
    if (BinaryIntegerConstants<T>.Seven == value) { yield break; }
    if (BinaryIntegerConstants<T>.Eleven == value) { yield break; }
    if (BinaryIntegerConstants<T>.Thirteen == value) { yield break; }

    var index = value;

    while (T.Zero == (index & T.One)/* enumerate factors of 2 */) {
        yield return BinaryIntegerConstants<T>.Two;

        index >>= 1;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Three)) { // enumerate factors of 3
        yield return BinaryIntegerConstants<T>.Three;

        index /= BinaryIntegerConstants<T>.Three;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Five)/* enumerate factors of 5 */) {
        yield return BinaryIntegerConstants<T>.Five;

        index /= BinaryIntegerConstants<T>.Five;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Seven)/* enumerate factors of 7 */) {
        yield return BinaryIntegerConstants<T>.Seven;

        index /= BinaryIntegerConstants<T>.Seven;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Eleven)/* enumerate factors of 11 */) {
        yield return BinaryIntegerConstants<T>.Eleven;

        index /= BinaryIntegerConstants<T>.Eleven;
    }
    while (T.Zero == (index % BinaryIntegerConstants<T>.Thirteen)/* enumerate factors of 13 */) {
        yield return BinaryIntegerConstants<T>.Thirteen;

        index /= BinaryIntegerConstants<T>.Thirteen;
    }

    var factor = BinaryIntegerConstants<T>.Seventeen;
    var limit = index.SquareRoot();

    if (factor <= limit) {
        do {
            while (T.Zero == (index % factor)/* enumerate factors of (30k - 13) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Two;

            while (T.Zero == (index % factor)/* enumerate factors of (30k - 11) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Four;

            while (T.Zero == (index % factor)/* enumerate factors of (30k - 7) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Six;

            while (T.Zero == (index % factor)/* enumerate factors of (30k - 1) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Two;

            while (T.Zero == (index % factor)/* enumerate factors of (30k + 1) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Six;

            while (T.Zero == (index % factor)/* enumerate factors of (30k + 7) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Four;

            while (T.Zero == (index % factor)/* enumerate factors of (30k + 11) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Two;

            while (T.Zero == (index % factor)/* enumerate factors of (30k + 13) */) {
                yield return factor;

                index /= factor;
            }

            factor += BinaryIntegerConstants<T>.Four;
            limit = index.SquareRoot();
        } while (factor <= limit);
    }

    if ((index != T.One) && (index != value)) {
        yield return index;
    }
}
羁客 2024-11-11 11:25:28

该版本以明确的公式列出了所有因素:

static void Main(string[] args)
    {
        Console.WriteLine("Please enter your integer (0 to stop): ");

        int a = int.Parse(Console.ReadLine());
        while(a>0)
        {
            List<int> primeFactors = PrimeFactors(a);
            LogFactorList(primeFactors);
            a = int.Parse(Console.ReadLine());
        }
        Console.WriteLine("Goodbye.");
    }


    /// <summary>
    /// Find prime factors
    /// </summary>
    public static List<int> PrimeFactors(int a)
    {
        List<int> retval = new List<int>();
        for (int b = 2; a > 1; b++)
        {               
            while (a % b == 0)
            {
                a /= b;
                retval.Add(b);
            }               
        }
        return retval;
    }

    /// <summary>
    /// Output factor list to console
    /// </summary>
    private static void LogFactorList(List<int> factors)
    {
        if (factors.Count == 1)
        {
            Console.WriteLine("{0} is Prime", factors[0]);
        }
        else
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < factors.Count; ++i)
            {
                if (i > 0)
                {
                    sb.Append('*');
                }
                sb.AppendFormat("{0}", factors[i]);
            }
            Console.WriteLine(sb.ToString());
        }
    }

This version lists all the factors as an explicit formula:

static void Main(string[] args)
    {
        Console.WriteLine("Please enter your integer (0 to stop): ");

        int a = int.Parse(Console.ReadLine());
        while(a>0)
        {
            List<int> primeFactors = PrimeFactors(a);
            LogFactorList(primeFactors);
            a = int.Parse(Console.ReadLine());
        }
        Console.WriteLine("Goodbye.");
    }


    /// <summary>
    /// Find prime factors
    /// </summary>
    public static List<int> PrimeFactors(int a)
    {
        List<int> retval = new List<int>();
        for (int b = 2; a > 1; b++)
        {               
            while (a % b == 0)
            {
                a /= b;
                retval.Add(b);
            }               
        }
        return retval;
    }

    /// <summary>
    /// Output factor list to console
    /// </summary>
    private static void LogFactorList(List<int> factors)
    {
        if (factors.Count == 1)
        {
            Console.WriteLine("{0} is Prime", factors[0]);
        }
        else
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < factors.Count; ++i)
            {
                if (i > 0)
                {
                    sb.Append('*');
                }
                sb.AppendFormat("{0}", factors[i]);
            }
            Console.WriteLine(sb.ToString());
        }
    }
妞丶爷亲个 2024-11-11 11:25:28
using static System.Console;

namespace CodeX
{
    public class Program
    {
        public static void Main(string[] args)
        {
            for (int i = 0; i < 20; i++)
            {
                if (IsPrime(i))
                {
                    Write($"{i} ");
                }
            }
        }

        private static bool IsPrime(int number)
        {
            if (number <= 1) return false;  // prime numbers are greater than 1

            for (int i = 2; i < number; i++)
            {
                // only if is not a product of two natural numbers
                if (number % i == 0)       
                    return false;
            }

            return true;
        }
    }
}
using static System.Console;

namespace CodeX
{
    public class Program
    {
        public static void Main(string[] args)
        {
            for (int i = 0; i < 20; i++)
            {
                if (IsPrime(i))
                {
                    Write($"{i} ");
                }
            }
        }

        private static bool IsPrime(int number)
        {
            if (number <= 1) return false;  // prime numbers are greater than 1

            for (int i = 2; i < number; i++)
            {
                // only if is not a product of two natural numbers
                if (number % i == 0)       
                    return false;
            }

            return true;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文