Dereference pointer to array of long from list iterator - c++

How do I correctly dereference pointers to arrays of long.
In the function main my code seems to print the addresses instead of the long values.
#include <list>
#include <iostream>
#include <cmath>
#include <vector>
bool
is_prime (long i)
{
// fix wrong return values for 0 and 1
if (i <= 1)
return false;
const long j = (long) std::sqrt(i);
for (long k=2; k<j+1; ++k) {
if (i % k == 0)
return false;
}
return true;
}
std::list<long(*)[2]>
goldbach (long number)
{
std::list<long(*)[2]> sums;
std::list<long(*)[2]>::iterator it;
if (number < 4) // Exclude too small integers.
return sums;
if (number % 2) // Exclude uneven numbers.
return sums;
it = sums.begin();
for (long candidate=2; candidate < number; ++candidate)
{
if (is_prime(candidate))
{
if (is_prime(number - candidate))
{
long sum[2];
sum[0] = candidate;
sum[1] = number - candidate;
std::cout << sum[0] << " + " << sum[1] << "\n";
sums.insert(it, &sum);
++it;
}
}
}
return sums;
}
int
main ()
{
std::list<long(*)[2]> sums;
std::list<long(*)[2]>::iterator it;
for(long i = 4; i < 100; i+=2)
{
std::cout << "### " << i << " ###" << "\n";
sums = goldbach(i);
for (it = sums.begin(); it != sums.end(); ++it)
{
long num1 = *((*it)[0]);
long num2 = *((*it)[1]);
std::cout << num1 << " + " << num2 << "\n";
}
std::cout << "\n\n";
}
}

Thanks to the comments I realized that arrays within lists are a bad idea in C++.
I changed my code to the following, which works:
#include <list>
#include <iostream>
#include <cmath>
#include <vector>
bool
is_prime (long i)
{
// fix wrong return values for 0 and 1
if (i <= 1)
return false;
const long j = (long) std::sqrt(i);
for (long k=2; k<j+1; ++k) {
if (i % k == 0)
return false;
}
return true;
}
std::list<std::pair<long, long>>
goldbach (long number)
{
std::list<std::pair<long, long>> sums;
std::list<std::pair<long, long>>::iterator it;
if (number < 4) // Exclude too small integers.
return sums;
if (number % 2) // Exclude uneven numbers.
return sums;
it = sums.begin();
long complement;
for (long candidate=2; candidate < number; ++candidate)
{
if (is_prime(candidate))
{
complement = number - candidate;
if (is_prime(complement))
{
std::pair<long, long> sum = std::make_pair(candidate, complement);
sums.insert(it, sum);
++it;
}
}
}
return sums;
}
int
main ()
{
std::list<std::pair<long, long>> sums;
std::list<std::pair<long, long>>::iterator it;
for(long i = 4; i < 100; i+=2)
{
std::cout << "### " << i << " ###" << "\n";
sums = goldbach(i);
for (it = sums.begin(); it != sums.end(); ++it)
{
std::cout << it->first << " + " << it->second << "\n";
}
std::cout << "\n\n";
}
}

Related

How to avoid loop removal with -O3 and the performance impact of asm("") when benchmarking a C++ code block?

I'm trying to microbenchmark the following C++ code, compiled with the -O3 g++ compiler option for maximum performance:
long long x = 0;
int iterations = 1000000;
int load = 1000;
for(int i = 0; i < iterations; i++) {
long start = get_nano_ts(&ts);
for(int j = 0; j < load; j++) {
long p = (i % 8) * (i % 16);
if (i % 2 == 0) {
x += p;
} else {
x -= p;
}
asm(""); // so that the loop is not removed by -O3
}
long end = get_nano_ts(&ts);
int res = end - start - nanoTimeCost;
if (res <= 0) res = 1;
// (...) removed for clarity
}
cout << "Value computed: " << x << endl;
As you can see I'm using the asm("") instruction to prevent the compiler from turning my loop calculation into something else. How do I know it is turning my loop calculation into something else? That's because without the asm("") line, the value is calculated immediately and the program exits immediately, no matter how large I make the load variable.
So my question is: How can I use the -O3 compiler option and still prevent it from turning my loop into something else?
From this SO question, I got that I have to use asm("") for that. But then my question becomes: Wouldn't asm("") mess with my timing (add overhead) and/or prevent the compiler from doing other valid/good optimizations like inlining?
Another solution for me would be to come up with a for/loop code that cannot be translated to a straight mathematical formula by the compiler, in other words, some kind of mathematical computation that really requires a loop to be executed. Any suggestions?
Below the full C++ code I'm using:
#include <iostream>
#include <string>
#include <random>
#include <cmath>
#include <algorithm>
#include <limits>
#include <sys/time.h>
#include <map>
#include <sched.h>
#include <sstream>
#include <iomanip>
using namespace std;
// TO COMPILE: g++ TestJitter.cpp -o TestJitter -std=c++11 -O3
// TO EXECUTE: ./TestJitter 10000000 1000000 1000 1
static const bool MORE_PERCS = true;
static const bool INCLUDE_WORST_PERCS = true;
static const bool INCLUDE_TOTALS = true;
static const bool INCLUDE_RATIOS = false;
static const bool INCLUDE_STDEV = true;
static const bool EXCLUDE_NANO_TS_COST = true;
long get_nano_ts(timespec* ts) {
clock_gettime(CLOCK_MONOTONIC, ts);
return ts->tv_sec * 1000000000 + ts->tv_nsec;
}
static const long NANO_COST_ITERATIONS = 10000000;
static long calc_nano_ts_cost() {
struct timespec ts;
long start = get_nano_ts(&ts);
long finish = start;
for (long i = 0; i < NANO_COST_ITERATIONS; i++) {
finish = get_nano_ts(&ts);
}
finish = get_nano_ts(&ts);
return (finish - start) / NANO_COST_ITERATIONS;
}
struct mi {
long value;
};
void add_perc(stringstream& ss, int size, double perc, map<int, mi*>* map) {
if (map->empty()) return;
int max = -1;
int minBottom = -1;
long x = round(perc * size);
long i = 0;
long iBottom = 0;
long sum = 0;
long sumBottom = 0;
bool trueForTopFalseForBottom = true;
bool flag = false;
const int arraySize = 1024 * 1024 * 10;
int* tempData = new int[arraySize];
double stdevTop = -1;
for(auto iter = map->begin(); iter != map->end(); iter++) {
if (flag) break;
int time = iter->first;
long count = (iter->second)->value;
for(int a = 0; a < count; a++) {
if (trueForTopFalseForBottom) {
tempData[i] = time;
i++;
sum += time;
if (i == x) {
max = time;
if (INCLUDE_STDEV) {
double avg = (double) sum / (double) i;
double temp = 0;
for(int b = 0; b < i; b++) {
int t = tempData[b];
temp += (avg - t) * (avg - t);
}
stdevTop = sqrt(((double) temp / (double) i));
}
if (INCLUDE_WORST_PERCS) {
trueForTopFalseForBottom = false;
} else {
flag = true;
break;
}
}
} else {
tempData[iBottom] = time;
iBottom++;
sumBottom += time;
if (minBottom == -1) {
minBottom = time;
}
}
}
}
ss << " | " << fixed << setprecision(5) << (perc * 100) << "%";
if (INCLUDE_TOTALS) ss << " (" << i << ")";
ss << " = [avg: " << (sum / i);
if (INCLUDE_STDEV) ss << ", stdev: " << fixed << setprecision(2) << stdevTop;
ss << ", max: " << max << "]";
if (INCLUDE_WORST_PERCS) {
ss << " - " << fixed << setprecision(5) << ((1 - perc) * 100) << "%";
if (INCLUDE_TOTALS) ss << " (" << (iBottom > 0 ? iBottom : 0) << ")";
ss << " = [avg: " << (iBottom > 0 ? (sumBottom / iBottom) : -1);
if (INCLUDE_STDEV) {
ss << ", stdev: ";
if (iBottom <= 0) {
ss << "?";
} else {
double avgBottom = (sumBottom / iBottom);
double temp = 0;
for(int b = 0; b < iBottom; b++) {
long t = tempData[b];
temp += (avgBottom - t) * (avgBottom - t);
}
double stdevBottom = sqrt((double) temp / (double) iBottom);
ss << fixed << setprecision(2) << stdevBottom;
}
}
ss << ", min: " << (minBottom != -1 ? minBottom : -1) << "]";
if (INCLUDE_RATIOS) {
ss << " R: ";
ss << fixed << setprecision(2) << (iBottom > 0 ? (((sumBottom / iBottom) / (double) (sum / i)) - 1) * 100 : -1);
ss << "%";
}
}
delete[] tempData;
}
int main(int argc, char* argv[]) {
int iterations = stoi(argv[1]);
int warmup = stoi(argv[2]);
int load = stoi(argv[3]);
int proc = stoi(argv[4]);
cpu_set_t my_set;
CPU_ZERO(&my_set);
CPU_SET(proc, &my_set);
sched_setaffinity(0, sizeof(cpu_set_t), &my_set);
long nanoTimeCost = EXCLUDE_NANO_TS_COST ? calc_nano_ts_cost() : 0;
struct timespec ts;
long long x = 0;
long long totalTime = 0;
int minTime = numeric_limits<int>::max();
int maxTime = numeric_limits<int>::min();
map<int, mi*>* results = new map<int, mi*>();
for(int i = 0; i < iterations; i++) {
long start = get_nano_ts(&ts);
for(int j = 0; j < load; j++) {
long p = (i % 8) * (i % 16);
if (i % 2 == 0) {
x += p;
} else {
x -= p;
}
asm(""); // so that the loop is not removed by -O3
}
long end = get_nano_ts(&ts);
int res = end - start - nanoTimeCost;
if (res <= 0) res = 1;
if (i >= warmup) {
totalTime += res;
minTime = min(minTime, res);
maxTime = max(maxTime, res);
auto iter = results->find(res);
if (iter != results->end()) {
(iter->second)->value = (iter->second)->value + 1;
} else {
mi* elem = new mi();
elem->value = 1;
(*results)[res] = elem;
}
}
}
int count = iterations - warmup;
double avg = totalTime / count;
cout << "Value computed: " << x << endl;
cout << "Nano timestamp cost: " << nanoTimeCost << endl;
stringstream ss;
ss << "Iterations: " << count << " | Avg Time: " << avg;
if (INCLUDE_STDEV) {
long temp = 0;
long x = 0;
for(auto iter = results->begin(); iter != results->end(); iter++) {
int time = iter->first;
long count = (iter->second)->value;
for(int a = 0; a < count; a++) {
temp += (avg - time) * (avg - time);
x++;
}
}
double stdev = sqrt( temp / x );
ss << " | Stdev: " << fixed << setprecision(2) << stdev;
}
if (count > 0) {
ss << " | Min Time: " << minTime << " | Max Time: " << maxTime;
}
add_perc(ss, count, 0.75, results);
add_perc(ss, count, 0.90, results);
add_perc(ss, count, 0.99, results);
add_perc(ss, count, 0.999, results);
add_perc(ss, count, 0.9999, results);
add_perc(ss, count, 0.99999, results);
if (MORE_PERCS) {
add_perc(ss, count, 0.999999, results);
add_perc(ss, count, 0.9999999, results);
}
cout << ss.str() << endl << endl;
delete results;
return 0;
}

Extra "0" in output when factorizing a number

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;
}

Print prime factorization in exponential form in C++

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.

Why does this C++ prime checker and summer return wrong results?

I don't get why the summation never works properly, yet sums consistently.
It dosent throw any errors, but never gets the correct result. According to wolfram|alpha i can be off with as much as 20 000 000 000 for large calculations. I have no idea why this happens, so any ideas you might have are greatly appreciated!
Note: Compiled with -O3 and -std=c++14 flags.
Code:
#include "stdafx.h"
#include <math.h>
#include <vector>
#include <stdio.h>
#include <iostream>
typedef unsigned long long ul;
const ul PRIMES = 1000000;
bool isPrime(ul n)
{
if (n <= 1) return false;
double sqN = sqrt(n);
for (ul i = 3; i <= sqN; i++) {
if ((int)n % i == 0) return false;
} return true;
}
int main()
{
std::vector<ul> primes;
ul sumPrimes = 0;
ul numPrimes = 0;
for (ul n = 2; n <= PRIMES; n++) if (isPrime(n)) primes.push_back(n);
numPrimes = primes.size();
for (ul sp : primes) sumPrimes += sp;
std::vector<ul> fizz, buzz, fizzbuzz;
ul sumF = 0, sumB = 0, sumFB = 0;
ul numF = 0, numB = 0, numFB = 0;
for (ul prime = 0; prime < primes.size(); prime++) {
if (prime % 15 == 0) {
fizzbuzz.push_back(primes[prime]);
}
else if (prime % 5 == 0) {
buzz.push_back(primes[prime]);
}
else if (prime % 3 == 0) {
fizz.push_back(primes[prime]);
}
}
for (ul fb : fizzbuzz) sumFB += fb;
for (ul f : fizz) sumF += f;
for (ul b : buzz) sumB += b;
numF = fizz.size(); numB = buzz.size(); numFB = fizzbuzz.size();
std::cout << "Stats for primes upto\t" << PRIMES << "\n";
std::cout << "Primecount:\t\t" << numPrimes << "\n";
std::cout << "Sum Primes:\t\t" << sumPrimes << "\n";
std::cout << "Fizzcount:\t\t" << numF << "\n";
std::cout << "Sum Fizz:\t\t" << sumF << "\n";
std::cout << "Buzzcount:\t\t" << numB << "\n";
std::cout << "Sum Buzz:\t\t" << sumB << "\n";
std::cout << "FizzBuzzcount:\t\t" << numFB << "\n";
std::cout << "Sum FizzBuzz:\t\t" << sumFB << "\n";
std::system("pause");
return 0;
}
And this is the output i get:
output
In your isPrime method, you are starting with i = 3. Start with i = 2 so that you are removing non primes that have a factor of 2.
bool isPrime(ul n)
{
if (n <= 1) return false;
double sqN = sqrt(n);
for (ul i = 3; i <= sqN; i++) {
if ((int)n % i == 0) return false;
} return true;
}
Try
bool isPrime(ul n)
{
if (n <= 1) return false;
double sqN = sqrt(n);
for (ul i = 2; i <= sqN; i++) {
if ((int)n % i == 0) return false;
} return true;
}
Unless I have misunderstood something.

Reprinting 2D array prime factors

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();
}