Binomial coefficient programm outputs wrong results, if inputs are large(C++) - c++

I have created a programm, that calculates binomial coefficient:
#include <iostream>
#include <string>
using namespace std;
int factorial(int num){
int res = 1;
for(int i = 1;i <= num; ++i){
res *= i;
}
return res;
}
int binom(int n,int k){
int factorial(int num);
int binom_coef;
binom_coef = factorial(n)/(factorial(k)*factorial(n-k));
return binom_coef;
}
int main(){
int n,k;
int binom(int n,int k);
try{
cout << "Enter number n:";
cin >> n;
cout << "Enter number k:";
cin >> k;
if(n < k){
throw -1;
}
cout << binom(n,k) << "\n";
}catch(int x)
cout << "n must be biggger than k";
}
For small inputs(up to 10) everything works perfectly fine. But if I enter big enough n and k(more than 10) the calculations are totally wrong and I cannot figure out why is that.
Can you help me?

The factorial is a function that grows really fast. It may be that for n > 10 your factorials already overflow the int type.
In fact, 12! = 479001600
You’re applying the theoretical formula for the binomial coefficient, but if you try the operative definition you may have less problems:
10 : 2 = 10! / (2! * 8!) = (10 * 9) / (2 * 1)
So what you can do is: multiply all numbers in [n, n - k), then divide them for all the numbers in [k, 1).
int bin_coeff(int n, int k) {
int res = 1, i = n;
while (i > n - k) res *= i--;
while (i > 0) res /= i--;
return res;
}
As you can see, you’ll calculate 10 : 2 by simply doing 90 / 2, which are not big numbers, and you’ll even get a better efficiency for your algorithm.

Related

Lares - Them divide c people into t groups

There is m men, and n women.The boss chooses k people. Them divide m+n-k remain people into t groups, each group exactly 2 men and 1 woman. Find max(t)
For example:
Input
264936043 821529140 438045170
Ouput
132468021
#include <iostream>
using namespace std;
int n, m, k, res, t;
int main(){
cin >> n >> m >> k;
for (int i = max(k-m, 0); i <= n; i++){
res = max(res, min((n-i)/2, m-k+i));
}
cout << res;
}
My code is TLE.
I think the number of men chosen is (n+2k-2m)/3 because (n-i) ~ 2*(m-k+i), but it is not correct.
Thank you #dratenik, I used derivative to analyze the function (n-x)/(m-k-x). And this is my accepted code.
#include <iostream>
using namespace std;
int n, m, k;
int main(){
cin >> n >> m >> k;
if (k >= m+n) cout << 0;
else if (n/2 <= m-k) cout << n/2;
else if ((n-k)/2 >= m) cout << m;
else {
int t = (n + 2*k - 2*m)/3;
cout << max(min((n-t)/2, m-k+t), min((n-t-1)/2, m-k+t+1));
}
}

How do I find the smallest number than can be divided by all numbers 1:n with no remainder?

I have been trying to solve problem number 5 on Project Euler which goes like
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I decided to go a step further and I decided I'd make it find the smallest positive number that is evenly divisible by all of the numbers from 1 to limit where limit is user-defined.
Problem starts when I execute my program, it immediately prints out 0. I tried tracing my code but that didn't work out.
#include <iostream>
using std::cout;
using std::cin;
bool isRemainderFree(int num, int limit){
bool bIsRemainderFree = true;
if(num < limit){
bIsRemainderFree = false;
}else{
for(int i=1; i <= limit; i++){
if(num % i != 0){
bIsRemainderFree = false;
break;
}
}
}
return bIsRemainderFree;
}
int smallestMultiple(int limit){
int smallestNum = 10;
for(int i=1; i <= limit; i++){
bool bFree = isRemainderFree(i, 10);
if(bFree){
cout << i << " is divisible by all numbers from 1 to " << limit << ".\n";
smallestNum = i;
return smallestNum;
break;
}
}
}
int main(){
int limit;
cin >> limit;
int smallestNum = smallestMultiple(limit);
cout << smallestNum;
return 0;
}
The answer should be simply the LCM of all numbers, it can be easily done in the following way
int gcd(int a, int b){
if(b==0)
return a;
return gcd(b, a%b);
}
int main() {
int limit = 10, lcm = 1;
for(int i=1; i<=limit; i++){
lcm = (lcm * i)/gcd(lcm,i);
}
printf("%d\n", lcm); // prints 2520
return 0;
}
PYTHON CODE
import math
# Returns the lcm of first n numbers
def lcm(n):
ans = 1
for i in range(1, n + 1):
ans = int((ans * i)/math.gcd(ans, i))
return ans
# main
n = 20
print (lcm(n))

Efficiently getting all divisors of a given number

According to this post, we can get all divisors of a number through the following codes.
for (int i = 1; i <= num; ++i){
if (num % i == 0)
cout << i << endl;
}
For example, the divisors of number 24 are 1 2 3 4 6 8 12 24.
After searching some related posts, I did not find any good solutions. Is there any efficient way to accomplish this?
My solution:
Find all prime factors of the given number through this solution.
Get all possible combinations of those prime factors.
However, it doesn't seem to be a good one.
Factors are paired. 1 and 24, 2 and 12, 3 and 8, 4 and 6.
An improvement of your algorithm could be to iterate to the square root of num instead of all the way to num, and then calculate the paired factors using num / i.
You should really check till square root of num as sqrt(num) * sqrt(num) = num:
Something on these lines:
int square_root = (int) sqrt(num) + 1;
for (int i = 1; i < square_root; i++) {
if (num % i == 0&&i*i!=num)
cout << i << num/i << endl;
if (num % i == 0&&i*i==num)
cout << i << '\n';
}
There is no efficient way in the sense of algorithmic complexity (an algorithm with polynomial complexity) known in science by now. So iterating until the square root as already suggested is mostly as good as you can be.
Mainly because of this, a large part of the currently used cryptography is based on the assumption that it is very time consuming to compute a prime factorization of any given integer.
Here's my code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
#define pii pair<int, int>
#define MAX 46656
#define LMT 216
#define LEN 4830
#define RNG 100032
unsigned base[MAX / 64], segment[RNG / 64], primes[LEN];
#define sq(x) ((x)*(x))
#define mset(x,v) memset(x,v,sizeof(x))
#define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31)))
#define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31)))
// http://zobayer.blogspot.com/2009/09/segmented-sieve.html
void sieve()
{
unsigned i, j, k;
for (i = 3; i<LMT; i += 2)
if (!chkC(base, i))
for (j = i*i, k = i << 1; j<MAX; j += k)
setC(base, j);
primes[0] = 2;
for (i = 3, j = 1; i<MAX; i += 2)
if (!chkC(base, i))
primes[j++] = i;
}
//http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
vector <pii> factors;
void primeFactors(int num)
{
int expo = 0;
for (int i = 0; primes[i] <= sqrt(num); i++)
{
expo = 0;
int prime = primes[i];
while (num % prime == 0){
expo++;
num = num / prime;
}
if (expo>0)
factors.push_back(make_pair(prime, expo));
}
if ( num >= 2)
factors.push_back(make_pair(num, 1));
}
vector <int> divisors;
void setDivisors(int n, int i) {
int j, x, k;
for (j = i; j<factors.size(); j++) {
x = factors[j].first * n;
for (k = 0; k<factors[j].second; k++) {
divisors.push_back(x);
setDivisors(x, j + 1);
x *= factors[j].first;
}
}
}
int main() {
sieve();
int n, x, i;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
primeFactors(x);
setDivisors(1, 0);
divisors.push_back(1);
sort(divisors.begin(), divisors.end());
cout << divisors.size() << "\n";
for (int j = 0; j < divisors.size(); j++) {
cout << divisors[j] << " ";
}
cout << "\n";
divisors.clear();
factors.clear();
}
}
The first part, sieve() is used to find the prime numbers and put them in primes[] array. Follow the link to find more about that code (bitwise sieve).
The second part primeFactors(x) takes an integer (x) as input and finds out its prime factors and corresponding exponent, and puts them in vector factors[]. For example, primeFactors(12) will populate factors[] in this way:
factors[0].first=2, factors[0].second=2
factors[1].first=3, factors[1].second=1
as 12 = 2^2 * 3^1
The third part setDivisors() recursively calls itself to calculate all the divisors of x, using the vector factors[] and puts them in vector divisors[].
It can calculate divisors of any number which fits in int. Also it is quite fast.
Plenty of good solutions exist for finding all the prime factors of not too large numbers. I just wanted to point out, that once you have them, no computation is required to get all the factors.
if N = p_1^{a}*p_{2}^{b}*p_{3}^{c}.....
Then the number of factors is clearly (a+1)(b+1)(c+1).... since every factor can occur zero up to a times.
e.g. 12 = 2^2*3^1 so it has 3*2 = 6 factors. 1,2,3,4,6,12
======
I originally thought that you just wanted the number of distinct factors. But the same logic applies. You just iterate over the set of numbers corresponding to the possible combinations of exponents.
so int he example above:
00
01
10
11
20
21
gives you the 6 factors.
If you want all divisors to be printed in sorted order
int i;
for(i=1;i*i<n;i++){ /*print all the divisors from 1(inclusive) to
if(n%i==0){ √n (exclusive) */
cout<<i<<" ";
}
}
for( ;i>=1;i--){ /*print all the divisors from √n(inclusive) to
if(n%i==0){ n (inclusive)*/
cout<<(n/i)<<" ";
}
}
If divisors can be printed in any order
for(int j=1;j*j<=n;j++){
if(n%j==0){
cout<<j<<" ";
if(j!=(n/j))
cout<<(n/j)<<" ";
}
}
Both approaches have complexity O(√n)
Here is the Java Implementation of this approach:
public static int countAllFactors(int num)
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
for (int i = 1; i * i <= num; i+=1)
{
if (num % i == 0)
{
tree_set.add(i);
tree_set.add(num / i);
}
}
System.out.print(tree_set);
return tree_set.size();
}
//Try this,it can find divisors of verrrrrrrrrry big numbers (pretty efficiently :-))
#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<conio.h>
using namespace std;
vector<double> D;
void divs(double N);
double mod(double &n1, double &n2);
void push(double N);
void show();
int main()
{
double N;
cout << "\n Enter number: "; cin >> N;
divs(N); // find and push divisors to D
cout << "\n Divisors of "<<N<<": "; show(); // show contents of D (all divisors of N)
_getch(); // used visual studio, if it isn't supported replace it by "getch();"
return(0);
}
void divs(double N)
{
for (double i = 1; i <= sqrt(N); ++i)
{
if (!mod(N, i)) { push(i); if(i*i!=N) push(N / i); }
}
}
double mod(double &n1, double &n2)
{
return(((n1/n2)-floor(n1/n2))*n2);
}
void push(double N)
{
double s = 1, e = D.size(), m = floor((s + e) / 2);
while (s <= e)
{
if (N==D[m-1]) { return; }
else if (N > D[m-1]) { s = m + 1; }
else { e = m - 1; }
m = floor((s + e) / 2);
}
D.insert(D.begin() + m, N);
}
void show()
{
for (double i = 0; i < D.size(); ++i) cout << D[i] << " ";
}
int result_num;
bool flag;
cout << "Number Divisors\n";
for (int number = 1; number <= 35; number++)
{
flag = false;
cout << setw(3) << number << setw(14);
for (int i = 1; i <= number; i++)
{
result_num = number % i;
if (result_num == 0 && flag == true)
{
cout << "," << i;
}
if (result_num == 0 && flag == false)
{
cout << i;
}
flag = true;
}
cout << endl;
}
cout << "Press enter to continue.....";
cin.ignore();
return 0;
}
for (int i = 1; i*i <= num; ++i)
{
if (num % i == 0)
cout << i << endl;
if (num/i!=i)
cout << num/i << endl;
}
for( int i = 1; i * i <= num; i++ )
{
/* upto sqrt is because every divisor after sqrt
is also found when the number is divided by i.
EXAMPLE like if number is 90 when it is divided by 5
then you can also see that 90/5 = 18
where 18 also divides the number.
But when number is a perfect square
then num / i == i therefore only i is the factor
*/
//DIVISORS IN TIME COMPLEXITY sqrt(n)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll int n;
cin >> n;
for(ll i = 2; i <= sqrt(n); i++)
{
if (n%i==0)
{
if (n/i!=i)
cout << i << endl << n/i<< endl;
else
cout << i << endl;
}
}
}
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define MOD 1000000007
#define fo(i,k,n) for(int i=k;i<=n;++i)
#define endl '\n'
ll etf[1000001];
ll spf[1000001];
void sieve(){
ll i,j;
for(i=0;i<=1000000;i++) {etf[i]=i;spf[i]=i;}
for(i=2;i<=1000000;i++){
if(etf[i]==i){
for(j=i;j<=1000000;j+=i){
etf[j]/=i;
etf[j]*=(i-1);
if(spf[j]==j)spf[j]=i;
}
}
}
}
void primefacto(ll n,vector<pair<ll,ll>>& vec){
ll lastprime = 1,k=0;
while(n>1){
if(lastprime!=spf[n])vec.push_back(make_pair(spf[n],0));
vec[vec.size()-1].second++;
lastprime=spf[n];
n/=spf[n];
}
}
void divisors(vector<pair<ll,ll>>& vec,ll idx,vector<ll>& divs,ll num){
if(idx==vec.size()){
divs.push_back(num);
return;
}
for(ll i=0;i<=vec[idx].second;i++){
divisors(vec,idx+1,divs,num*pow(vec[idx].first,i));
}
}
void solve(){
ll n;
cin>>n;
vector<pair<ll,ll>> vec;
primefacto(n,vec);
vector<ll> divs;
divisors(vec,0,divs,1);
for(auto it=divs.begin();it!=divs.end();it++){
cout<<*it<<endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
sieve();
ll t;cin>>t;
while(t--) solve();
return 0;
}
We can use modified sieve for getting all the factors for all numbers in range [1, N-1].
for (int i = 1; i < N; i++) {
for (int j = i; j < N; j += i) {
ans[j].push_back(i);
}
}
The time complexity is O(N * log(N)) as the sum of harmonic series 1 + 1/2 + 1/3 + ... + 1/N can be approximated to log(N).
More info about time complexity : https://math.stackexchange.com/a/3367064
P.S : Usually in programming problems, the task will include several queries where each query represents a different number and hence precalculating the divisors for all numbers in a range at once would be beneficial as the lookup takes O(1) time in that case.
java 8 recursive (works on HackerRank). This method includes option to sum and return the factors as an integer.
static class Calculator implements AdvancedArithmetic {
public int divisorSum(int n) {
if (n == 1)
return 1;
Set<Integer> set = new HashSet<>();
return divisorSum( n, set, 1);
}
private int divisorSum(int n, Set<Integer> sum, int start){
if ( start > n/2 )
return 0;
if (n%start == 0)
sum.add(start);
start++;
divisorSum(n, sum, start);
int total = 0;
for(int number: sum)
total+=number;
return total +n;
}
}

Need to calculate series equation converging to π

First time programming and I’ve got to write a program that calculates the series equation
(n!)^2*2^n+1/(2n+1)!, n being the amount of terms the user inputs.
I’ve got it to where the user inputs n and I get the answer for that number only.
How do I make it so that I get the sum of all answers from 0 to the user input?
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
double i,n,factorial,factorial2,n2,a;
a = 1;
cout<<"Enter # of terms:";
cin>>n;
for (i = 0; i <= n; i++)
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
factorial = pow(factorial,2)*pow(2,n+1);
n2 = 2*n+a;
for (i = 0; i <= n2; i++)
if (i == 0)
factorial2 = 1;
else
factorial2 = factorial2 * i;
factorial = factorial/factorial2;
cout<<factorial<<endl;
system("PAUSE");
}
Here's the code from my comments, all laid out to be readable...
#include <iostream>
#include <cmath>
int factorial(int n)
{
return n <= 1 ? 1 : factorial(n - 1) * n;
}
OR if you find that factorial function confusing, SlySherZ suggested this beginner-friendly alternative (you don't want both implementations).
int factorial(int n)
{
if (n <= 1)
return 1;
return factorial(n - 1) * n;
}
Continuing...
double f(double n)
{
return std::pow(fact(n),2) * std::pow(2, n) + 1 / factorial(2 * n + 1);
}
int main()
{
double n, total = 0;
while (std::cin >> n)
total += f(n);
std::cout << "total " << total << '\n';
}
You have two options:
Use a loop that will go through each n;
Make a recursive function:
// In pseudocode
term (n){
if ( n < 0 ) return 0;
// calculate y for this n;
return y + term( n - 1 );
}
A recursive function (assuming you're familiar with functions) is a function that calls itself to solve a problem. For example, n! = (n - 1)! * n. You can use this simple fact an create a factorial function f ( n ) that returns n * f ( n - 1 ) unless n is 1 (returns 1 in this case).
I'll develop the first option:
// I assumed your code is working and that factorial holds the values you want to sum.
// If that's not the case, I believe you can use it to solve your problem anyway
#include <iostream>
#include<cmath>
using namespace std;
int main() {
double n, total = 0;
cout << "Enter # of terms:";
cin >> n;
while (n >= 0) {
double i, factorial, factorial2, n2, a;
a = 1;
for (i = 0; i <= n; i++) {
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
}
factorial = pow(factorial, 2)*pow(2, n + 1);
n2 = 2 * n + a;
for (i = 0; i <= n2; i++) {
if (i == 0)
factorial2 = 1;
else
factorial2 = factorial2 * i;
factorial = factorial / factorial2;
}
total += factorial;
n--;
}
cout << total << endl;
}
Hope it helps :D

Error "expected primary-expression before int"

I'm writing a code that will (hopefully) allow the user to input a number, and which will output the sum of the prime numbers between 2 and that number (inclusive). I'm getting one problem, however, on the penultimate line of the code. I've looked up other solutions to this question, but they don't seem to be caused by the same error as mine. Here's the code:
#include <iostream>
using namespace std;
int Q;
int sum_primes(int N) {
cout << "Enter a number and I will generate the sums of the primes up to (and including) that number: ";
cin >> Q;
int i, count, sum = 0;
for(N = 1; N <= Q; N++) {
count = 0;
for(i = 2; i <= N/2; i++) {
if (N % i == 0) {
count++;
break;
}
}
if (count == 0 && N != 1)
sum = sum + N;
return N = sum;
}
}
int main() {
cout << "The sum of these primes is: " << sum_primes(int N);
return 0;
}
cout << "..." << sum_primes(int N);
Replace int N with a number. You already defined the function, now you need to give it a parameter.
Or maybe you wanted to give N's value through user input. Then use this instead:
int N;
cin >> N;
cout << "The sum of these primes is: " << sum_primes(N);
Also, as GigaWatt pointed out, the line on which you did:
return N = sum;
is unnecessary. Simply returning sum will work just as well.
Here's the complete code:
#include <iostream>
#include <cmath>
bool isPrime(int x) {
if (x == 1) return false;
if (x == 2) return true;
bool prime = true;
for (int i = 2; i <= sqrt(x); i++) {
if (x % i == 0) { prime = false; break; }
}
return prime;
}
int sum_primes(unsigned int N) {
int sum = 0;
for ( int i = 1; i <= N; i++ ) {
if (isPrime(i)) sum += i;
}
return sum == 0 ? 1 : sum;
}
int main() {
int Q;
std::cin >> Q;
std::cout << "Sum of primes " << sum_primes(Q);
}
There are in fact multiple issues with this code. I'll list a few, but this is by no means exhaustive!
You've got some slightly crazy structuring of your code there. I guess this will become apparent when you fix the simple syntax error. Just as a point of style, I'd pass in Q as an argument to sum_primes as well as N.
You're outputting "The sum of these primes is" before asking "Enter a number".
return N = sum will exit your outer for-loop immediately. This is almost certainly not what you wanted.
I suspect you'll need to hunt down a better instroduction to C++ than you're currently working from. I'm afraid I can't offer you any advice with that.
Your argument to sum_primes is incorrect.
The function is defined to take an int, but you're not passing it one.