second largest factor

need to find the second largest factor but my function keeps returning 1 all the time.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int second_largest_factor(int n)
{
	int secondLargest=1;
	
	int i = 0;
	int count = 0;
	while( i < n/2  && count < 2)
	{
		if (n%i == 0 )
		{
			secondLargest = i;
			count++;
			i--;
		}

	}
	return secondLargest;
}

int main ()
{
	int f = 48;
	cout << second_largest_factor(f) << endl;
}
Last edited on
your while loop never starts because you set i = n/2 yet you want you loop to start when i is less than n/2...and on top of that you have another condition...

the second condition is met but the first condition is never met...

the && symbol means that both conditions have to be met for the while loop to execute.
Last edited on
made change, still doesnt work
Sorry it doesn't work..I didn't know the solution but I just figured I would let you know that logic error in the code..

If you can please comment your code so I can better understand how you are thinking this out and what you expect to happen.
Last edited on
i got it now man. anyways thanks for the help; appreciate it.
this was the sol

int second_largest_factor(int n)
{
int secondLargest=1;

int i = n/2;
int count = 0;
while( i >0 && count < 2)
{
if (n%i == 0 )
{
secondLargest = i;
count++;

}
i--;

}
return secondLargest;
}
Topic archived. No new replies allowed.