Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C# (http://www.programmingforums.org/forum16.html)
-   -   One more thing I'd like to do (http://www.programmingforums.org/showthread.php?t=13654)

357mag Jul 29th, 2007 2:07 PM

One more thing I'd like to do
 
I've got this program that inputs an integer and then outputs the prime factorization. Here is the code:

:

using System;

public class WhileLoop
{
    public static void Main()
    {
        int number;

        Console.Write("Enter an integer: ");
        number = Convert.ToInt32(Console.ReadLine());

        for (int i = 2; i <= number;)
        {
            if (number % i == 0)
            {
                Console.Write(i + " * ");
                number = number / i;
            }

            else
                i++;
        }

        Console.WriteLine();
    }
}


I want the program to not only output the prime numbers, but I want to show the multiplication symbol between the numbers. But the problem is that I end up with one too many symbols. I've deduced that I need one less multiplication symbol than I have digits. So if there are 7 digits output, all I need is 6 symbols. If there are 4 digits output, all I need is 3 symbols. I want the output to look like this, say for the factorization of 20:

2 * 2 * 5

And like this for the factorization of 150:

2 * 3 * 5 * 5

I don't know how to do it though.

Booooze Jul 29th, 2007 2:14 PM

Well, if you stored it in a string, you could just chop off the last * symbol. Or I think you could just throw another if statement in there within the loop and current if statement. Have it check to see if you on the last loop , if so, write i instead of i + *. Will that work?

357mag Jul 29th, 2007 2:53 PM

I'd need to see some specific code. I don't know what to write.

357mag Jul 29th, 2007 3:17 PM

Wait. I think I got it figured out and it appears to be working. I did this:

:

if (number % i == 0)
{
    if (i == number)
      Console.Write(i);

    else
      Console.Write(i + " * ");
        number = number / i;
}



All times are GMT -5. The time now is 2:51 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC