So far I have this code. I'm trying to print prime factorization with exponents. For example, if my input is 20, the output should be 2^2, 5
#include <iostream>
#include <cmath>
using namespace std;
void get_divisors (int n);
bool prime( int n);
int main(int argc, char** argv) {
int n = 0 ;
cout << "Enter a number and press Enter: ";
cin >>n;
cout << " Number n is " << n << endl;
get_divisors(n);
cout << endl;
return 0;
}
void get_divisors(int n){
double sqrt_of_n = sqrt(n);
for (int i =2; i <= sqrt_of_n; ++i){
if (prime (i)){
if (n % i == 0){
cout << i << ", ";
get_divisors(n / i);
return;
}
}
}
cout << n;
}
bool prime (int n){
double sqrt_of_n = sqrt (n);
for (int i = 2; i <= sqrt_of_n; ++i){
if ( n % i == 0) return 0;
}
return 1;
}
I hope someone can help me with this.
You can use an std::unordered_map<int, int> to store two numbers (x and n for x^n). Basically, factorize the number normally by looping through prime numbers smaller than the number itself, dividing the number by the each prime as many times as possible, and recording each prime you divide by. Each time you divide by a prime number p, increment the counter at map[p].
I've put together a sample implementation, from some old code I had. It asks for a number and factorizes it, displaying everything in x^n.
#include <iostream>
#include <unordered_map>
#include <cmath>
bool isPrime(const int& x) {
if (x < 3 || x % 2 == 0) {
return x == 2;
} else {
for (int i = 3; i < (int) (std::pow(x, 0.5) + 2); i += 2) {
if (x % i == 0) {
return false;
}
}
return true;
}
}
std::unordered_map<int, int> prime_factorize(const int &x) {
int currentX = abs(x);
if (isPrime(currentX) || currentX < 4) {
return {{currentX, 1}};
}
std::unordered_map<int, int> primeFactors = {};
while (currentX % 2 == 0) {
if (primeFactors.find(2) != primeFactors.end()) {
primeFactors[2]++;
} else {
primeFactors[2] = 1;
}
currentX /= 2;
}
for (int i = 3; i <= currentX; i += 2) {
if (isPrime(i)) {
while (currentX % i == 0) {
if (primeFactors.find(i) != primeFactors.end()) {
primeFactors[i]++;
} else {
primeFactors[i] = 1;
}
currentX /= i;
}
}
}
return primeFactors;
}
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
auto factors = prime_factorize(x);
std::cout << x << " = ";
for (auto p : factors) {
std::cout << "(" << p.first << " ^ " << p.second << ")";
}
}
Sample output:
Enter a number: 1238
1238 = (619 ^ 1)(2 ^ 1)
To begin with, avoid using namespace std at the top of your program. Second, don't use function declarations when you can put your definitions before the use of those functions (but this may be a matter of preference).
When finding primes, I'd divide the number by 2, then by 3, and so on. I can also try with 4, but I'll never be able to divide by 4 if 2 was a divisor, so non primes are automatically skipped.
This is a possible solution:
#include <iostream>
int main(void)
{
int n = 3 * 5 * 5 * 262417;
bool first = true;
int i = 2;
int count = 0;
while (i > 1) {
if (n % i == 0) {
n /= i;
++count;
}
else {
if (count > 0) {
if (!first)
std::cout << ", ";
std::cout << i;
if (count > 1)
std::cout << "^" << count;
first = false;
count = 0;
}
i++;
if (i * i > n)
i = n;
}
}
std::cout << "\n";
return 0;
}
Note the i * i > n which is an alternative to the sqrt() you are using.
Related
Write a function int fact(int n) which displays the factors of the integer n, and returns the number of factors. Call this function in main() with user input
#include<iostream>
using namespace std;
int fact(int n);
int main() {
int n,factor;
cout << "Enter an integer : ";
cin >> n;
factor = fact(n);
cout << factor;
return 0;
}
int fact(int n)
{
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
cout << i << endl;
}
return 0;
}
If I enter 7, I get 1,7,0 . How do i remove this 0 and how do i find the number of factors?
You should count in your int fact() function. Set a variable to 0 and increment each time you currently display i. Then at the end of the function instead of returning 0 return the count variable.
int fact(int n)
{
int count=0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
count++;
}
}
return count;
}
The key part is "and returns the number of factors". You don't do that. Keep a count of the factors:
int fact(int n)
{
int count = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
{
// found a factor, add to the count
count++;
cout << i << endl;
}
}
// return the count instead
return count;
}
Then, your main function can use that count:
factor = fact(n); // fact(n) will already print the factors
// now just print the number
cout << "Number of factors: " << factor << '\n';
#include <iostream>
#include <vector>
std::vector<int> fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
std::vector<int> factors = fact(n);
for (auto i : factors) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "Number of factors: " << factors.size() << '\n';
return 0;
}
std::vector<int> fact(int n) {
std::vector<int> vec{1};
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
vec.push_back(i);
}
}
vec.push_back(n);
return vec;
}
If you're going to return anything from fact(), it should be the factors. To do so, I am using a std::vector. It is an array that can grow on demand. The numbers 1 and n are always factors, so I don't bother doing the math for them. The vector is initialized already holding the value 1, and I only calculate numbers up to and including half of n (Anything greater than n/2 won't divide evenly, so my loop is finished about half as fast by recognizing the actual range). I then just add n to the vector, which I return.
My main prints the vector, and the vector knows its own size, which is the number of factors.
Alternatively, you can just keep a count in your fact() function.
#include <iostream>
#include <vector>
// Prints factors of n and returns the number of factors
int fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
int numFactors = fact(n);
std::cout << "Number of factors: " << numFactors << '\n';
return 0;
}
int fact(int n) {
int factorCount = 2; // Already counting 1 and n
std::cout << "1 ";
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
std::cout << i << ' ';
++factorCount;
}
}
std::cout << n << '\n';
return factorCount;
}
The main problem with your code is that your function always returns zero. You need to keep a count of factors and return it.
Besides that your code performance badly as the loop goes on much longer than needed. You can use the square root of n as the limit in the for loop. Like:
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int limit = sqrt(n);
for (int i = 1; i <= limit; ++i)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
}
if (limit * limit == n)
{
--res;
}
return res;
}
For n = 36 the output is:
1 - 36
2 - 18
3 - 12
4 - 9
6 - 6
and the returned value is 9
Below is another approach. It doesn't use square root. Instead it keeps the number of loops low by using the square of i as loop limit.
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int i = 1;
int i_square = i * i;
while (i_square < n)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
++i;
i_square = i * i;
}
if (i_square == n)
{
++res;
cout << i << " - " << n/i << endl;
}
return res;
}
Fact() always returns 0 so this line print 0
cout << factor;
for the number of factors you can change the return value of fact() :
int fact(int n)
{
int nb = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
nb++;
}
}
return nb;
}
a beginner at coding here.
I was practising loops(c++) when I stumbled upon this problem:-
Write a program in C++ to find the perfect numbers between 1 and 500. (6,28 and 496)
Perfect number: It is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.
I wrote the following code:-
#include <iostream>
using namespace std;
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
}
return 0;
}
The code is supposed to print that 6, 28 and 496 are perfect numbers.
But instead, it's not printing anything. Haven't been able to find the error yet after checking for 30+ minutes.
Could anyone point out the error?
You forget to re-initialize some variables in your loop.
for seems more appropriate than while here.
Create sub function also help to "identify" scope.
#include <iostream>
bool isPerfectNumber(int n)
{
int sum = 0;
for (int div = 1; div != n; ++div) {
if (n % div == 0) {
sum += div;
}
}
return sum == n && n > 0;
}
int main()
{
for (int i = 2; i != 501; ++i) {
if (isPerfectNumber(i)) {
std::cout << n << " is a perfect number." << std::endl;
}
}
return 0;
}
#include<iostream>
using namespace std;
bool perfect_num(int x);
int main() {
int m, n, x;
cout << "input the range m, n: " << "\n";
cin >> m >> n;
for (x = m; x <= n; ++x) {
if (perfect_num(x)) {
cout << x << " ";
}
}
return 0;
}
bool perfect_num(int x) {
bool flag = false;
//initialize
int sum = 0, i;
//loop 1 to x
for (i = 1; i < x; ++i) {
//judge whether is the factor
if (x % i == 0) {
sum += i;
}
}
//update flag
flag = (sum == x);
return flag;
}
#include<iostream>
using namespace std;
//judge function
bool isPerfectNum(int num){
int tmp = 0;
for (int i = 1; i < num; ++i) {
if (num % i == 0) {
tmp += i;
}
}
return tmp == num;
}
int main(){
cout << "Perfect Number contains: ";
for (int i = 1; i <= 500; ++i){
if (isPerfectNum(i)) {
cout << i << " ";
}
}
cout << "\n";
return 0;
}
at the end of your first loop, you should bring back div and sum to their default value.
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
div = 1; // you should bring them back here.
sum = 0;
}
return 0;
}
Sorry this is my first time use stackoverflow.
I dont kow where is the mistake in my code.
Output that i want:
-1+3-5+7-9+11-13+15
RESULT : 8
But Output that is shown
-1+3-5+7-9+11-13+15
RESULT : 10
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
cout << "+";
}
if (i == 1) {
sign = 1;
cout << "-";
}
x = sign * (2 * i - 1);
cout << x;
S = S + x;
}
cout << "\n Result:" << S;
}
problem is in the if condition block where you check i==1
in that loop you are making sign=1 that should be sign=-1
How about improving the logic like following?
#include <iostream>
using namespace std;
int main()
{
int i;
bool sign = true; // signed/minus = true, non-signed/plus = false
int ans = 0;
for( i=1; i<=15; i=i+2){
if( sign == true){
cout << "-" << i;
ans = ans - i;
}
else {
cout << "+" << i;
ans = ans + i;
}
sign = !sign;
}
cout << endl << "RESULT : " << ans << endl;
return 0;
}
Try this code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
else
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
// cout << "+";
}
//else
if (i == 1) {
sign = -1;
//cout << "-";
}
x = sign * (2 * i - 1);
cout <<"\n"<<x;
S = S + x;
//cout<<"S is \n"<<S;
}
cout << "\n Result:" << S;
}
You have put wrong sign when i==1
The problem is that you're starting the calculation with a positive sign (but you're lying to yourself by printing "-").
You can simplify the code and don't need to mess around with pow if you make the obervation that
pow(-1, k) == -1 * pow(-1, k-1)
Starting at pow(-1,0) (that is, 1), you can write:
int main(int argc, char* argv[])
{
int sign = 1; // sign will always hold pow(-1, i).
int sum = 0;
for (int i = 1; i <= 8; i++)
{
sign *= -1;
if (sign > 0) // Since sign starts at -1, we know that i > 1 here
{
std::cout << "+";
}
int term = sign * (2 * i - 1);
std::cout << term;
sum += term;
}
std::cout << " = " << sum << std::endl;
}
I'm trying to modify this program to their equivalent iterative but it becomes very difficult to me because as yet i'm still a newbie, it comes to an algorithm that decomposes a number into its prime factors, here the code:
#include <iostream>
#include <map>
#include <cmath>
std::map< int, std::pair<int, int> > decompositions;
void descompon_number(int num, int root, int i = 2 )
{
auto iterator = decompositions.find(num);
if (iterator == decompositions.end())
{
if (num > 1 && i <= root)
{
if (num % i == 0)
{
int n = num / i;
decompositions[num] = std::make_pair(i, n);
descompon_number(n, (int) std::sqrt(n));
}
else
descompon_number(num, root, i + 1);
}
else
decompositions[num] = std::make_pair(num, 1);
}
}
void show(int num, int factor, int exponent, int see)
{
auto pair = decompositions[num];
if (num <= 1 || factor != pair.first)
{
if (see)
std::cout << factor;
if (exponent > 1 && see)
std::cout << "^" << exponent;
if (pair.first > 1 && see)
std::cout << " * ";
exponent = 0;
}
if (num > 1)
show(pair.second, pair.first, exponent + 1, see);
}
void descompon(int a, int b, int see)
{
if (a <= b)
{
descompon_number(a, (int) std::sqrt(a));
if (see)
std::cout << a << " = ";
show(a, decompositions[a].first, 0, see);
if (see)
std::cout << std::endl;
descompon(a + 1, b, see);
}
}
int main()
{
descompon(2, 100, 1);
return 0;
}
Someone can help me out with this
Finding prime factors iteratively is not very complicated.
Here's the pseudocode how to do this.
Let P be a list of the first n prime numbers, such that Pn <= sqrt(m).
array findPrimeFactors(m)
answer = new array
for p in P
while m can be divided by p
m = m / p
answer.append(p)
if m == 1
break
return answer
Note: empty array is returned if m is prime.
You can use an erastotenes' sieve to compute prime numbers, and later you can use the algorithm posted by popovitsj.
The following code can be optimized, but its main purpose is to show you how to proceed.
Complete example:
#include <iostream>
#include <vector>
using namespace std;
// Returns a vector containing the first <number> prime numbers
vector<int> erastotenes_sieve(int number)
{
vector<int> result;
int *sieve = new int[number];
for (int i = 0; i < number; i++) sieve[i] = 0;
// Traverse the sieve marking multiples.
for (int i = 2; i < number / 2; i++)
for (int j = i + i; j < number; j += i)
sieve[j] = 1;
// Collect unaffected indexes, those are prime numbers.
for (int i = 2; i < number; i++)
if (!sieve[i])
result.push_back(i);
delete [] sieve;
return result;
}
vector<int> descompon_number(int number)
{
vector<int> result;
if (number == 1 || number == 0)
{
result.push_back(number);
return result;
}
for (int &prime : erastotenes_sieve(number))
{
while (number % prime == 0 && number != 1)
{
number /= prime;
result.push_back(prime);
}
}
return result;
}
int main()
{
for (auto &i : descompon_number(20))
{
cout << i << endl;
}
return 0;
}
I am writing a parallel prime factorization program in C++. I managed to get all of the threading and finding out the prime pretty well but its the very end that I can't seem to get. When the user enters more than one number to find the prime factor of, it prints the entire array of prime factorization. I want it to only print the prime factors related to a unique number.
I would like to change it to where the line after "The prime factorization of 10 is" doesn't print the entire vector of prime numbers. All of the printing occurs towards the bottom of the main function. To be very specific, if I were to type in two 10's, the output should be:
---desired output---
"The prime factorization of 10 is"
"2 5"
"The prime factorization of 10 is"
"2 5"
---/desired output---
do not worry about the "there are: 0 prime numbers" part. I know how to fix that already
Any and all help is appreciated!
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <mutex>
#include <list>
#include <algorithm>
using namespace std;
using namespace std::chrono;
int userInput; // This number is used to help store the user input
vector<long long> vec(0); // A vector storing all of the information
int numPrimes; // Used to count how many prime numbers there are
bool PRINT = false; // lets me decide if I want to print everything for debugging purposes
int arraySize;
vector<thread> threads;
vector<vector<long long> > ending;
void getUserInput()
{
//while the user has not entered 0, collect the numbers.
cout << "Please enter a number for prime factorization. Enter 0 to quit" << endl;
do
{
cin >> userInput;
if (userInput != 0)
{
vec.push_back(userInput);
arraySize++;
}
} while (userInput != 0);
}
vector<long long> primeFactors(long long n)
{
vector<long long> temp;
while (n % 2 == 0)
{
temp.push_back(n);
numPrimes++;
n = n / 2;
}
for (int i = 3; i <= sqrt(n); i = i + 2)
{
while (n%i == 0)
{
temp.push_back(n);
numPrimes++;
n = n / i;
}
}
if (n > 2)
{
temp.push_back(n);
numPrimes++;
}
return temp;
}
void format()
{
cout << endl;
}
bool isPrime(long long number){
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i = 3; (i*i) <= number; i += 2){
if (number % i == 0) return false;
}
return true;
}
vector<long long> GetPrimeFactors(long long num)
{
vector<long long> v;
for (int i = 2; i <= num; i++)
{
while (num % i == 0)
{
num /= i;
v.push_back(i);
}
}
return v;
}
int main()
{
// how to find out how many cores are available.
getUserInput();
high_resolution_clock::time_point t1 = high_resolution_clock::now();
// vector container stores threads
format();
for (int i = 0; i < arraySize; ++i)
{
vector<long long> temp;
threads.push_back(thread([&]
{
ending.push_back(GetPrimeFactors(vec.at(i)));
}));
}
// allow all of the threads to join
for (auto& th : threads)
{
th.join();
}
for (int i = 0; i < arraySize; ++i)
{
cout << "The prime factorization of " << vec.at(i) << " is \n" << endl;
for (int m = 0; m < ending.size(); m++)
{
vector<long long> v = ending[m];
for (int k = 0; k < v.size(); k++)
{
cout << v.at(k) << " ";
}
}
cout << endl;
}
format();
cout << "There are: " << numPrimes << " prime numbers" << endl;
//time
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(t2 - t1).count();
format();
cout << "Time in seconds: " << (duration / 1000000.0) << endl;
format();
}
This was too long for a comment so, I'm posting this as an answer
You could also try this
#include <iostream>
using namespace std;
long long Number;
int Prime[10000];
void Gen()
{
Prime[0]=2;
Prime[1]=3;
bool IsPrime;
long long Counter=2;
for( int ii=4 ; Counter<10000 ; ii++ )
{
IsPrime=true;
for( int jj=0 ; Prime[jj]<=sqrt(ii) ; jj++ )
{
if(ii%Prime[jj]==0)
{
IsPrime=false;
break;
}
}
if(IsPrime)
{
Prime[Counter]=ii;
Counter++;
}
}
}
int main()
{
int Factor[10000]={0};
Gen();
cout<<"Enter Number"<<endl;
cin>>Number;
Factorize :
for( int ii=0 ; ii<10000 ; ii++ )
{
if(Number<Prime[ii])
{
break;
}
if(Number%Prime[ii]==0)
{
Number/=Prime[ii];
Factor[ii]=1;
if(Number==1)
{
break;
}
goto Factorize;
}
}
for( int ii=0 ; ii<10000 ; ii++ )
{
if(Factor[ii])
{
cout<<Prime[ii]<<" ";
}
}
}
Well, what I'm doing is I'm first generating array of primes, then I'm dividing given Number from elements of Prime array. If Number is divisible by respective prime factor then I'm marking it's index in factor array as a factor, Then I'm iterating over factor array, if any element is marked as factor then I'm printing it.
Actually, You can adjust number of elements in array as per your requirements.
So I figured it out:
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
int userInput; // This number is used to help store the user input
vector<long long> vec(0); // A vector storing all of the information
int numPrimes; // Used to count how many prime numbers there are
int arraySize;
vector<thread> threads;
vector<vector<long long> > ending;
void getUserInput()
{
//while the user has not entered 0, collect the numbers.
cout << "Please enter a number for prime factorization. Enter 0 to quit" << endl;
do
{
cin >> userInput;
if (userInput != 0)
{
vec.push_back(userInput);
arraySize++;
}
} while (userInput != 0);
}
void format()
{
cout << endl;
}
bool isPrime(long long number){
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i = 3; (i*i) <= number; i += 2){
if (number % i == 0) return false;
}
return true;
}
vector<long long> GetPrimeFactors(long long num)
{
vector<long long> v;
for (int i = 2; i <= num; i++)
{
while (num % i == 0)
{
num /= i;
v.push_back(i);
numPrimes++;
}
}
return v;
}
int main()
{
// how to find out how many cores are available.
getUserInput();
high_resolution_clock::time_point t1 = high_resolution_clock::now();
// vector container stores threads
format();
for (int i = 0; i < arraySize; ++i)
{
vector<long long> temp;
threads.push_back(thread([&]
{
ending.push_back(GetPrimeFactors(vec.at(i)));
}));
}
// allow all of the threads to join
for (auto& th : threads)
{
th.join();
}
for (int i = 0; i < arraySize; ++i)
{
cout << "The prime factorization of " << vec.at(i) << " is \n" << endl;
vector<long long> temp = ending[i];
for (int m = 0; m < temp.size(); m++)
{
cout << temp.at(m) << " ";
}
cout << endl;
}
format();
cout << "There are: " << numPrimes << " prime numbers" << endl;
//time
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(t2 - t1).count();
format();
cout << "Time in seconds: " << (duration / 1000000.0) << endl;
format();
}