Thread: Largest prime factor and number of prime factors for a number

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    7

    Unhappy Largest prime factor and number of prime factors for a number

    Hi guys... i need some help getting the following code to display how many prime factors there are for a number (in this case the number is represented by a) and also the largest prime factor of that same number. At the moment, it displays all of the prime factors. Any help would be great.


    Code:
        for(p1 = 1; p1 <= a; p1++)
         {
               for(p2 = (a / 2); p2 > 0; p2--) 
                {
                      if (p1 * p2 == a)
                      {
                             cout << p2 << endl;
                                }
                        }
                        }
    Last edited by Jas11; 03-29-2005 at 07:11 AM.

  2. #2
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    Here is a little something to get you started. You should be able to easily edit this function that will return a list of all prime factors for a given number.

    Once you have a list of all prime factors, it should be easy to get the total number of factors.. and then use a sorting algorithm to determine the largest prime factor.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  3. #3
    Slave MadCow257's Avatar
    Join Date
    Jan 2005
    Posts
    735
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int a = 100, numfactors = 0;
    	for (int p1 = 1; p1 <= a; p1++)
    	{
    		for (int p2 = (a / 2); p2 > 0; p2--) 
    		{
    			if (p1 * p2 == a)
    			{
    				numfactors++;
    				if (numfactors == 1)
    					cout << "The greatest factor of " << a << " is " << p2;
    			}
    		}
    	}
    	cout << "\n" << a << " Has " << numfactors << " factors.\n";
    	return 0;
    }
    BTW...
    you should use a different algorithm for finding factors IMO

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    Thanks alot guys... that has been a huge help

Popular pages Recent additions subscribe to a feed