#include <iostream>
#include <string>
usingnamespace std;
bool chk(int i);
string prime = " is already a prime number";
string factor = " is a prime factor";
int main()
{
loop3:
cout << "Enter Number:\n";
int i;
cin >> i;
if (chk(i) == true)
{
cout << i << prime << endl;
}
else
{
int x = 2;
int r = 0;
loop:
if (i%x == 0)
{
cout << x << factor << endl;
i = i / x;
r = r + x;
goto loop;
}
else
{
int z = 3;
loop2:
if (z != i)
{
if (i%z == 0)
{
cout << z << factor << endl;
i = i / z;
r = r + z;
goto loop2;
}
else
{
z = z + 1;
goto loop2;
}
}
else
{
cout << z << factor << endl;
r = r + z;
cout << r << " is the Sum of all Prime Factors" << endl;
if (chk(r) == true)
{
cout << "The Sum is a Prime" << endl;
}
else
{
cout << "The Sum is NOT a Prime" << endl;
}
}
}
}
loop4:
cout << "try again? Y or N?" << endl;
string input;
cin >> input;
if (input == "Y")
{
goto loop3;
}
else
{
if (input == "N")
{
return 0;
}
else
{
cout << "What? Please Enter Correctly" << endl;
goto loop4;
}
}
system("pause");
}
bool chk(int i)
{
for (int x = 2; x < i; x++)
{
if (i%x == 0)
{
returnfalse;
}
}
returntrue;
}
Do you have any suggestion about this?
I am new in C++,
and I am Happy with the output.
is there anything unnecessary in my code?
Please tell me.
is there anything unnecessary in my code?
Please tell me.
The goto statement is unnecessary, learn to use the other more accepted loop statements like do{}, do{}while(); and for( ; ; ) along with functions and meaningful variable names.
// Program to print all prime factors
#include <iostream>
#include <cmath>
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n % 2 == 0)
{
std::cout << "2 ";
n = n / 2;
}
// n must be odd at this point. So we can skip one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i + 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
std::cout << i << ' ';
n = n / i;
}
}
// This condition is to handle the case when n is a prime number
// greater than 2
if (n > 2)
std::cout << n << ' ';
}
/* Driver program to test above function */
int main()
{
int n = 1000;
primeFactors(n);
return 0;
}