简体   繁体   中英

Is a given number a prime or not, if not output all its divisors

The main part of my code is working, the only thing that doesn't work is the output of all its divisors. My result if it's not a prime should be like this: Input -> 4 Output -> false 1 2 4

Console.WriteLine("Type your number: ");
int n = Convert.ToInt32(Console.ReadLine());
int a = 0, i;
for (i = 1; i <= n; i++)
{
    if (n % i == 0)
    {
        a++;
    }
}

if (a == 2)
{
    Console.WriteLine("true");
}
else
{
    Console.WriteLine("false" + i);
}
Console.ReadLine();

Here is a working solution. You basically have to store your divisors somewhere or print them directly:

public static void Method(int n)
    {
        if (IsPrime(n))
        {
            Console.WriteLine($"{n} is a prime");
            return;
        }

        var divisors = new List<int>();

        for(var i = 1; i <= n; i++)
        {
            if (n % i == 0)
                divisors.Add(i);
        }

        Console.WriteLine($"{n} isn't a prime");
        Console.WriteLine($"The divisors are: {string.Join(", ", divisors)}");
    }

    public static bool IsPrime(int n)
    {
        for(var i = 2; i < n; i++)
        {
            if (n % i == 0)
                return false;
        }

        return true;
    }

From a brief inspection, there are two ways to generate the output. So far, you count the number of divisors, but neither store them nor write them to the output. You could replace

if (n % i == 0)
{
    a++;
}

by

if (n % i == 0)
{
    Console.WriteLine(i);
    a++;
}

or store the divisors in a

List<int>

to generate the output afterwards.

To print all the divisors, you'll need to gather them up in a collection of some sort – a list of integers, here.

In addition, all integers are divisible by 1 , so you don't want to start there; neither do you want to end at n , since n % n == 0 .

var divisors = new List<int>();
for (var i = 2; i < 2; i++)
{
    if (n % i == 0)
    {
        divisors.Add(i);
    }
}
if (divisors.Count == 0)
{
    Console.WriteLine("true");
}
else
{
    Console.WriteLine("false " + String.Join(" ", divisors));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM