![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
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. |
|
|
|
|
|
#2 |
|
Expert Programmer
|
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?
|
|
|
|
|
|
#3 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
I'd need to see some specific code. I don't know what to write.
|
|
|
|
|
|
#4 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
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;
}Last edited by 357mag; Jul 29th, 2007 at 2:19 PM. Reason: mistake |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| What is this 'if __name__ == '__main__'' thing? | commodore | Python | 2 | Apr 30th, 2006 3:46 PM |
| Last thing you had for supper. | Eric the Red | Coder's Corner Lounge | 22 | Apr 17th, 2006 11:02 AM |
| some funky string array thing | Intimidat0r | C# | 2 | Nov 24th, 2005 7:18 AM |
| Basic thing | zzk | C++ | 4 | Mar 21st, 2005 10:35 AM |
| Strange Fraction Thing | gamehack | C++ | 2 | Mar 6th, 2005 6:19 PM |