I came up with a bit of code that I think will theoretically factor any given integer within the range of integers. I'm posting this thread to ask two questions: First, is there any way that I can do this more efficiently, and second, what is the easiest way to do this using arrays. Thank you in advance for your helpful feedback, and I hope this thread can help some people (including myself) get all the more proficient at coding. So here's the code I came up with:

 #include "stdafx.h"
 #include <iostream>
 #include <string>
using namespace std;

int main(void) {

    string againloop("Yes");
    do {
        int number;
        int factor(2);
        cout << "Please enter a number to be factored." << endl;
        cin >> number;
        cout << "The factors of your number are:" << endl;
        do{
            if (number % factor == 0){
                number = number / factor;
                cout << factor << endl;
            }
            else {
                factor++;
            }
        }
        while (number != 1);

        cout << endl << "Factor another number?" << endl;
            cin >> againloop;
    }
    while (againloop == "yes"||"Yes"||"YES"||"y"||"Y");
        return 0;
}

First, is there any way that I can do this more efficiently, ...

First thing is compile the program and fix the errors. There's generally no reason to enhance a program that won't compile in the first place or runs improperly.

...and second, what is the easiest way to do this using arrays.

Completely depends on what you need the arrays for. Just adding arrays for the sake of adding arrays is not a good idea. I can see at least two ways you might add arrays. Come up with a reason and the way usually shows itself.

One way that I can immediately see is that you only need to look for factors up to number / 2, instead of number like you currently do. That should give you a factor of 2 speed up in total run-time Another thing would be to make your search multi-threaded.

There are many algorithms for factorization, and is a prime topic for research. You may want to check out this and this.
Google for more information.

Member Avatar for Kwetal

You only need to check factors up to sqrt(number).
Also, all possible factors > 2 are odd, so you might consider skipping even factors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.