I'm trying to write a program that calculates the largest prime factor for a number entered by the user,the function "FindFactor" calculates the largest factor which is stored in the variable "Factor" and the function "TestFactor" tests to see how many factors THAT factor has,which is then stored in "NFactors",if "NFactors" equals 0,Factor is a prime factor,if not,the initial input value is replaced with "Factor" and the loop starts again.
The problem is the ouput for any given number is the largest factor for the input not the prime factor.
After some tinckering,I have confirmed that the problem is in "TestFactor" as "FindFactor" is able to calculate the largest factor correctly,but I have no idea why "TestFactor" always outputs 0,as the two functions are practically identical.
Things get even weirder when I tried to use a debugger,(but this is probably due to the fact that this is my first time using it and I have no idea what I'm doing):
I set a break point to "NF",a local contained in "TestFactor",to see it's value and I get a message telling me "identifier "i" is undefined","i" being a local variable contained in "FindFactor" the function that actually works correctly.
Then I set a breakpoint to "NFactors" and this time I get the following exception:"Unhandled exception at 0x00A01D9D in Largest Prime Factor.exe: 0xC0000094: Integer division by zero."
referring to the following operation:
if (y % j == 0)
Which is definetly not the case,as j=y-1.
Here's the full program:
#include <iostream>
using namespace std;
int FindFactor(int x);
int TestFactor(int y);
int main() {
int input, Factor, NFactors,inputsave; bool prime=false;
cout << "Please enter a number" << endl;
cin >> input;
inputsave = input;
while (prime == false) {
Factor = FindFactor(input);
NFactors = TestFactor(Factor);
if (NFactors != 0) {
prime = true;
}
else {
prime = false;
input = Factor;
}
}
cout << "The largest prime factor for " << inputsave << " is " << Factor << endl;
}
int FindFactor(int x) {
int i;
for (i = x - 1; i > 1; i--) {
if (x % i == 0) {
break;
}
else {};
}
return i;
}
int TestFactor(int y) {
int j, NF = 0;
for (j = y - 1; j > 1; j--) {
if (y % j == 0) {
NF++;
}
else {};
}
return NF;
}
To Summarize:
"TestFactor":Output is always 0.
Main Program:Output is always the largest factor of the input,not prime factor.
There is a typo in TestFactor, use j > 1 as the condition for the loop.
User contributions licensed under CC BY-SA 3.0