Prime factors program problem

1. Dec 8, 2011

rollcast

I'm trying to write a program that will find and then display the prime factor of a number.

I have written this in C# but it works for some numbers but doesn't work for others?

Code (Text):
using System;

class primefactors
{
public static void Main()
{
int number;
bool isprime = true;

Console.WriteLine("Please enter the number you wish to find the prime factors of:");

Console.WriteLine("The prime factors of {0} are;", number);

for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
for (int j = 2; j < i; j++)
{
if (i % j == 0 && i != j)
{
isprime = false;
}
}

if (isprime == true)
{
Console.WriteLine(i);
}
}

}
Console.WriteLine("Press ANY Key to continue");
}
}

2. Dec 8, 2011

rollcast

Sorry I think I just fixed it

Code (Text):

using System;

class primefactors
{
public static void Main()
{
int number;
bool isprime = true;

Console.WriteLine("Please enter the number you wish to find the prime factors of:");

Console.WriteLine("The prime factors of {0} are;", number);

for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
for (int j = 2; j < i; j++)
{
if (i % j == 0 && j != i)
{
isprime = false;
}
}

if (isprime == true)
{
Console.WriteLine(i);
}

isprime = true;
}

}
Console.WriteLine("Press ANY Key to continue");
}
}

3. Dec 8, 2011

Xitami

Code (Text):
using System;
class primefactors {
public static void Main() {
int number;
Console.WriteLine("Please enter the number you wish to find the prime factors of:");
Console.WriteLine("The prime factors of {0} are;", number);

for ( int i = 2; i*i <= number;  i+=i=='}'-'{'?'/'/'/':1<<1 )
if ( number % i == 0) {           // i += 1 + i & 1;
Console.WriteLine( i );
while( number%i == 0 )
number /= i; }
if( number != 1 )
Console.WriteLine( number );

Console.WriteLine("Press ANY Key to continue");
}

Last edited: Dec 8, 2011
4. Dec 8, 2011

I like Serena

@Xitami: nice optimalization... but... what happens if I enter the number 4?

5. Dec 8, 2011

<= :-)

6. Dec 8, 2011