15

特定の入力の素因数を計算するプログラムを 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();



    }
}
4

6 に答える 6

50
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!");

Works on my machine!

于 2011-05-03T17:12:34.153 に答える
4
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.

于 2016-01-28T09:44:39.460 に答える
4

除数は数値の平方根よりも大きくなることはできないため、1 つ良くすることができます。

 for(int div = 2; div <= Math.Sqrt(number); div++)
于 2016-09-19T10:00:12.383 に答える
-1
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;
        }
    }
}
于 2020-04-13T15:31:28.510 に答える