Prime Factorization
hello guys. I need help. I am making a program that will output all pime factors of an integer.
This is my code
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 28 29
|
#include<iostream>
#include<cmath>
using namespace std;
bool isPrime(int n)
{
if(n < 2)
return false;
for(int m = 2 ; m <= sqrt(n) ; m++)
{
if (n % m == 0)
return false;
}
return true;
}
int main()
{
int x = 32, y, p;
cout << x << " = ";
for(y = 2; y <= x/2; y++){
p=x%y;
if(isPrime(p) && p!=0)
cout << p << " x ";
}
return 0;
}
|
my output is this
32 = 2 x 2 x 2 x 5 x 2 x 2 x |
it should be like this
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include<iostream>
#include<cmath>
bool isPrime(int);
bool isPrime(int n)
{
if(n < 2)
return false;
for(int m = 2; m <= sqrt(n); m++)
{
if (n % m == 0)
return false;
}
return true;
}
int main()
{
int x = 32;
std::cout << x << " = ";
if (isPrime(x)) std::cout << x << std::endl;
else
{
for (int y = 1; y < x; y++)
{
if (isPrime(y) && x % y == 0)
{
x /= y;
std::cout << y << " * ";
y--; //counter-act y++
}
if (x == 2) std::cout << 2 << std::endl;
}
}
return 0;
}
}
|
Last edited on
thank you sir for the help.
i made another code:
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 28
|
#include <iostream>
using namespace std;
int main()
{
long long int num;
while(cin >> num){
if(num<=1)
cout << num << " is unexpected input";
else
cout << num << " = ";
for (int i=2; i <= num; i++)
{
while(num % i == 0)
{
num /= i;
cout << i;
cout << " x ";
}
}
cout << endl;
}
return 0;
}
|
and my input is this
and the output is this
345
345 = 3 x 5 x 23 x
-2
-2 is unexpected input
32
32 = 2 x 2 x 2 x 2 x 2 x
4294967295
4294967295 = 3 x 5 x 17 x 257 x 65537 x |
my problem now is the extra 'x' at the end of each equation. How will I remove them?
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 28 29 30 31
|
#include <iostream>
int main()
{
long long int num;
while(std::cin >> num)
{
if(num <= 1)
{
std::cout << num << " is unexpected input" << std::endl;
continue;
}
std::cout << num << " = ";
for (int i = 2; i <= num; i++)
{
while(num % i == 0)
{
num /= i;
std::cout << i;
if (num > 1)
std::cout << " x ";
else
std::cout << std::endl;
}
}
}
return 0;
}
|
Thank you very much sir for the help!!
no problem :]
Topic archived. No new replies allowed.