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;
}
Related
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.
I'm trying to get the following output:
Enter integer: 87240
Missing digits: 1 3 5 6 9
Here is my code so far:
// Extract numbers inside integer n
while (numOfDigits > 0)
{
int digit = n % 10;
int missing = 0;
while ((digit != missing) && (missing < 10))
{
cout << missing << " ";
missing++;
}
numOfDigits--;
n /= 10;
}
which prints out
Enter integer: 87240
Missing digits: 0 1 2 3 0 1 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7
Is there any way to go about doing this without using an array?
Here is an implementation that uses a single integer (acc) to remember which digits had been seen:
#include <iostream>
using uuint = unsigned long long int;
uuint p(uuint n) { ++n; return n * n - n + 41; }
void print_missing(uuint n)
{
std::cout << "Number " << n << " is missing the following digits:";
uuint acc = 1;
while (n)
{
uuint q = p(n % 10);
if (acc % q != 0) acc *= q;
n /= 10;
}
for (int i = 0; i != 10; ++i)
{
if (acc % p(i) != 0) std::cout << " " << i;
}
std::cout << "\n";
}
int main()
{
for (uuint n; std::cin >> n; )
print_missing(n);
}
You can use a for loop, no need for an array:
#include <string>
#include <iostream>
#include <cstdlib>
int main()
{
std::string integer;
std::cout << "Enter integer: ";
std::getline(std::cin, integer);
for (unsigned int i = 0; i < 10; ++i)
{
const char c = '0' + i;
if (integer.find(c) == std::string::npos)
{
cout << i << " ";
}
}
return EXIT_SUCCESS;
}
The above version keeps the number in text form, easier to search for digits.
You could use a nested loop to check every digit of the number.
Are you interested in using a string instead of an array, perchance? Those are more or less the same idea, but given the input string n we could find any unused digits like this:
const auto digits = "0123456789"s;
sort(begin(n), end(n));
set_difference(cbegin(n), cend(n), cbegin(digits), cend(digits), ostream_iterator<char>(cout, " "));
Live Example
Here the version using a single integer to accumulate the results (still, technically array of bits):
#include <iostream>
#include <cmath>
void check(int n)
{
unsigned short bits = 0;
while (n) {
bits |= 1 << std::abs(n % 10);
n /= 10;
}
std::cout << "Missing digits:";
for (unsigned i = 0; i != 10; ++i) {
if (((bits >> i) & 1) == 0)
std::cout << " " << i;
}
std::cout << std::endl;
}
int main()
{
int n;
std::cout << "Enter a number: ";
std::cin >> n;
check(n);
return 0;
}
No Arrays in this one.
#include <stdio.h>
int NumHasDigit(int num, int digit)
{
while (num)
{
if (num%10 == digit)
{
return 1;
}
num /= 10;
}
return 0;
}
int main(void) {
int x;
printf("Enter int: ");
scanf("%d\n", &x);
printf("Missing Digits:\n");
for(int i=0; i<10; ++i)
{
if (!NumHasDigit(x,i)) printf("%d ", i);
}
return 0;
}
Sample Input:
34567
Sample Output:
Missing Digits
0 1 2 8 9
Ok, so I was doing a tiny project for school and I can't find the answer anywhere to why this small change in code makes it finish in no time when number m gets higher. Look at the variable "k" I change it from int to long.
I'm trying to find the longest sequence in the Collatz sequence between 1 and 1000000
void lengstaRuna() {
cout << "Hæsta tala?:";
int m;
cin >> m;
int lengstaRuna = 0;
int talaLengstuRunu = 0;
int k;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
void lengstaRuna() {
cout << "Hæsta tala?:";
int m;
cin >> m;
int lengstaRuna = 0;
int talaLengstuRunu = 0;
long k;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
The question is simple: Why does it run so much faster when input m==1000000?
I see what's happening here. Basically, above certain value for your input, the int is overflowing since you are doing k*3.
I modified your code to check this (see below). Upto input value of around 113000, the max your 'k' has to hold is 1570824735 (close to INT_MAX 2147483647). Anything 114000 or above, 'k' overflows and the code goes into uncharted territory. That problem doesn't happen when you use long of course.
./a.out 113000
j: 1570824735
Lengsta runa: 354
Tala lengstu runu: 106239
#include <iostream>
#include <string>
using namespace std;
void lengstaRuna(int m) {
int lengstaRuna = 0;
int talaLengstuRunu = 0;
int k;
long j = 0;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
if (k*3 > j)
j = k*3;
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "j: " << j << endl;
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
int main (int ac, char** av) {
std::string::size_type sz;
lengstaRuna(std::stoi(av[1]));
}
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();
}
I'm trying to write a function that would return a prime factorisation of a given number (as part of solving project euler's problem #12). To count the prime factors. I use std::map.
The code is as follows:
#include "stdafx.h"
#include <iostream>
#include <map>
#include <algorithm>
bool IsPrime(unsigned int number)
{
if (number < 1) return 0; // zero is not prime. For our purposes, one would be.
for (unsigned int i = 2; i*i <= number; ++i)
{
if (number % i == 0)
return false;
}
return true;
}
int divisors(unsigned int num)
{
int orig_num = num;
std::map <int, int> primefactors;
for(unsigned int i = 1; i <= num; ++i)
if (num % i == 0 && IsPrime(i))
{
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
std::cout << orig_num << " = ";
for(auto& iter:primefactors)
std::cout << iter.first << "^" << iter.second << " * ";
return 0;
}
int main()
{
divisors(661500);
return 0;
}
The problem is that all the counts of primefactors are returned as 1s, although the number in main was chosen specifically to be a product of primes to larger than 1 powers (661500 = 1^1*2^2*3^3*5^3*7^2).
My guess is that I'm incrementing something wrong.
You are dividing only once per prime. But you should continue dividing by the prime as long as number is divisible by it:
for(unsigned int i = 2; i <= num; ++i)
if (IsPrime(i))
{
while (num % i == 0) {
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
}
Actually there is no need for IsPrime(i) condition:
for(unsigned int i = 2; i <= num; ++i)
while (num % i == 0) {
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
Proof: if i is not a prime, then condition num % i == 0 implies that num is divisible by a prime factor p of i. But p < i so our loop had to go through p some time before i. And while loop would effectively erase all occurences of p in num. In particular by the time that for reaches i we have that num is no longer divisible by p. Contradiction. I.e. in the loop above if num % i == 0 is satisfied, then i is prime.