Sorry for bad English.
So my problem is that i need to find all possible factorials starting from 1.
I need it to stop when Int have maximum memory used and print out maximum factorial value. My code is pretty simple, but i do not know how to get to stop loop when it reach maximum of Intiger values.
#include <iostream>
#include<climits>//
#include <cmath>
using namespace std;
int main() {
int k,n=0;
unsigned int factorial = 1;
unsigned int factorial2=1;
unsigned uval=INT_MAX;
cout << "Ievadi koeficentu k: ";
cin >> k;
for(int i = 1; i<=k; ++i) {
factorial *= i;
}
cout << "Ievadita koeficenta " << k << " faktorials " << " = " <<factorial;
cout << "\nVisi iespejamie faktoriali no 1 - n: ";
for(int s = 1; s<=uval; ++s) {
factorial2 *= s;
if( s < uval / factorial2 ){
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
}
}
return 0;
}
The problem is that the loop is going to calculate factorial to all UINT_MAX values, and most of the output will be 0 becouse memory is overloaded.
But it should stop before it goes bigger that UINT_MAX memory!
Hope you all understand my problem and will help me with this.
In a 32-bit signed integer, 12! is the largest possible.
You can check this by doing
if (INT_MAX / fact_so_far < n)
{
std::cout << "Max factorial " << n-1 << std::endl;
}
[This code STOPS when it reaches the "unable to calculate", because INT_MAX / fact_so_far will not multiply without overflow].
if (INT_MAX / fact_so_far >= n)
{
fact_so_far *= n;
}
else
{
std::cout << n << " is too large to calculate factorial" << std::endl;
}
would be the other way to do this. [Obviously with suitable loop to increment n]
Not that MAX_UINT is the max value for unsigned int, not for int [it's typically half that].
Edit to explain the logic:
The logic here is that if we divide INT_MAX with what our current factorial value is, it should produce a value larger than n [the current multiplier for the next factorial].
As a simple step through example, we pick a MAX_INT of 127:
Initial state:
factorial = 1, n = 1;
Steps:
n = 2, MAX_INT / factorial = 127 -> factorial *= n => 2
n = 3, MAX_INT / factorial = 63 -> factorial *= n => 6
n = 4, MAX_INT / factorial = 21 -> factorial *= n => 24
n = 5, MAX_INT / factorial = 5 -> factorial *= n = 120
n = 6, MAX_INT / factorial = 1 -> FAIL - will overflow.
Before calculating the next factorial in the list, see if the previous one is greater than UINT_MAX / i. If it is, you know that the next multiplication will go out of bounds.
If factorial2 > UINT_MAX / (s+1), the next factorial can't be calculated.
By the way, you should use unsigned int for factorial2
You are comparing the signed int with an unsigned one i.e. you are doing i < UINT_MAX (This is the maximum value of unsigned int) which is wrong and will result in overflow and wrong condition check.
so i finaly did this with my code. Now it works but its not realy good. Maybe someone someday will need something like this as a start for his own max factorial programm. First program will ask you to insert a random number and then it calculate its factorial (only in max int borders). Then it prints out all possible int factorials. Its show only 11! as max but the max is 12! I add factorial 12! manualy, becouse the if statment cannot print out excatly the number 12 as max it prints one before. And in the end the programm shows you what is maxium possible factorial for intiger.
#include <iostream>
#include<climits>//
#include <cmath>
using namespace std;
int main() {
int k, max,s;
unsigned int factorial = 1;
unsigned int factorial2 = 1;
unsigned uval=INT_MAX;
cout << "Ievadi koeficentu k: ";
cin >> k;
for(int i = 1; i<=k; ++i) {
factorial *= i;
}
cout << "Ievadita koeficenta " << k << " faktorials " << " = " <<factorial;
cout << "\nVisi iespejamie faktoriali no 1 - n: ";
for( s = 1; s<=uval; ++s) {
factorial2 *= s;
max=factorial2;
if( s <= uval / factorial2 ){
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
}
else {
break;
}
}
cout <<" \nkoeficenta " << s << " faktorials ir ==> " <<factorial2;
cout <<" \nMaksimalais faktorials ir skaitla " << s << " faktorials ==> " <<max;
return 0;
}
This is what the programm looks like!
![Programm][1]
Related
#include <iostream>
using namespace std;
int enough(int goal)
{
int C { };
int i { };
if (goal > 1)
{
while (((C += i) <= goal) && ((goal - i) <= (i + 1)))
{
i += 1;
}
}
else
{
i = 1;
}
return i;
}
int main()
{
cout << enough(21);
return 0;
}
So the purpose of this function is for it to return the smallest positive integer that can be summed consecutively from 1 before the cumulative sum becomes greater than the parameter "goal".
So, for example:
cout << enough(9) << endl;
will print 4 because 1+2+3+4 > 9 but 1+2+3<9
cout << enough(21) << endl;
will print 6 'cause 1+2+ . . .+6 > 21 but 1+2+ . . . 5<21
cout << enough(-7) << endl;
will print 1 because 1 > -7 and 1 is the smallest positive integer
cout << enough(1) << endl;
will print 1 because 1 = 1 and 1 is the smallest positive integer
My logic at first was using just while ((C += i) <= goal), but that went wrong, for example, for the parameter 21, where you get C = 20, which passes the test and ends up in i being augmented by 1 (resulting in the return value i = 7, which is clearly wrong).
Therefore I decided to create a test which tested both C and i, but that went wrong because the code isn't considering goal - i and i + 1 as separate tests for the while circuit, but I believe it is actually altering the value of ints goal and i, which screws everything up.
Any ideas where I went wrong?
Your approach is unnecessarily verbose. There is a closed-form (i.e. O(1)) solution for this.
The sum S of the arithmetic progression 1, 2, ..., n is
S = n * (n + 1) / 2
Rearranging this (completing the square), rejecting the spurious root, and rounding appropriately to fit the requirements of the question yields the result
n = std::ceil((-1 + std::sqrt(1 + 8 * S)) / 2)
This will not work for negative n, and possibly 0 too depending on the specific (and unspecified) requirements.
Or if you must use an O(N) approach, then
int enough(int goal){
int i = 0;
for (int total = 0; (total += ++i, total) < goal; );
return i;
}
will do it, which returns 1 for goal <= 1.
You could perhaps try to simplify your original O(N) approach by only having one condition in your while-loop, i.e., no &&:
#include <iostream>
using namespace std;
int enough(int goal)
{
if (goal <= 0)
{
return 1;
}
int total{};
int i{};
while (total < goal)
{
total += ++i;
}
return i;
}
int main()
{
cout << "enough(9): " << enough(9) << endl;
cout << "enough(21): " << enough(21) << endl;
cout << "enough(-7): " << enough(-7) << endl;
cout << "enough(1): " << enough(1) << endl;
cout << "enough(0): " << enough(0) << endl;
return 0;
}
Output:
enough(9): 4
enough(21): 6
enough(-7): 1
enough(1): 1
enough(0): 1
Total Noob here, I am having a hard time with an assignment. I am taking a beginner course in C++ and have to figure out how to calculate the sum of negative integers and their avg. Sum of positive integers and the avg. And the sum of all numbers and the avg. I have gotten the last part already but how do I calculate the sum of negative integers and avg, and positive integers and avg using a while loop?
I provided my code below.
#include <iostream>
using namespace std;
#include <iomanip>
int main(int argc, const char * argv[]) {
int x;
double avg = 0.0;
int count = 0;
int sum = 0;
// ask users for input
cout << ("Welcome to the greatest calculator!\n");
cout << ("Please enter 10 integers seperated by spaces \n");
do {
std::cin >> x;
sum = sum + x;
count = count + 1;
}
while (count < 10);
// calculate average
avg = sum/10.0;
// output average
cout << fixed;
cout << "For all 10 numbers the sum is " << sum << "." "The average is " << setprecision (2) << sum/10.0 <<".\n";
return 0;
}
The output should look something like this.
Please enter 10 integers separated by spaces:
1 -1 45 17 28 -2 0 9 -14 11
Upon our intelligent calculations, here is the result:
+ There are 7 positive numbers, sum = 111.00 and average = 15.86
+ There are 3 negative numbers, sum = -17.00 and average = -5.67
+ For all 10 numbers, sum = 94.00 and average = 9.40 */
Use two variable int negativeVar=0 , PositiveVar=0 . In the loop try a condition if(GivenNumber<0) to detect the given number is negative or positive. Then add all positive and negative value separately and make avarage.
(Sorry for bad english)
You can do like this (notice comments):
#include <iostream>
int main(void) {
// Declaration and initialization of the required variables
float cPositive = 0.0f;
float cNegative = 0.0f;
int it = 0;
std::cout << "Enter 10 numbers (floating point assignable): \n";
// Looping till 10 iterations
do {
float temp;
std::cin >> temp;
// If the number is greater than zero, i.e. (+ve) then cPositive sums up
// otherwise, cNegative
if (temp > 0) cPositive += temp;
else if (temp <= 0.0f) cNegative -= temp;
} while (++it < 10); // Increment and comparison together
// Final results
std::cout \
<< "Sum of positive: " << cPositive << std::endl
<< "Sum of negative: -" << cNegative << std::endl;
return 0;
}
A simple test case:
Enter 10 numbers (floating point assignable):
10.5
-1.5
2.2
5.5
-3.8
-99.3
10
4.5
-1.0
0
Sum of positive: 32.7
Sum of negative: -105.6
Moreover, if you want to see average, then declare two variables, pos and neg where both are initially zero. After that, when a positive number or negative number occurs, just increment pos or neg and divide with them by cPositive or cNegative respectively.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// lets declare some variable first.
int positiveSum =0; //this will hold sum of positive nums
int negativeSum =0; // this will hold sum of negative nums
int totalSum =0; // this will hold sum of all the nums
int number=0; // user input for number
for (int i = 1; i <=10; i++) // loop from 1 to 10 times
{
cout << " Enter a number: ";
cin >> number;
// now check if number is positive or negative
if (number >=0)
{
positiveSum += number; // adds this number to positiveSum
}
else if (number < 0)
{
negativeSum += number; // adds this number to negativeSum
}
}
// So finally add the positiveSum and negativeSum to get the totalSum
totalSum = positiveSum + negativeSum;
cout << endl;
cout << " Total of Positive numbers is: " << positiveSum << endl;
cout << " Total of Negative numbers is: " << negativeSum << endl;
cout << " Total of all numbers is: " << totalSum << endl;
return 0;
}
The code below produces the following output:
$ ./main
The (sum, avg) of negative integers = (-15, -5)
The (sum, avg) of positive integers = (6, 2)
The (sum, avg) of all numbers = (-9, -1.5)
Please read the comments because they are in fact the detailed answer.
#include <array>
#include <iostream>
int main()
{
// For convenience, keep the numbers in an std::array. std::vector is
// equally convenient.
std::array<int, 6> integers { 1, -4, 2, -5, 3, -6 };
// Define variables that store the sums and the counts.
int positiveSum = 0;
int positiveCnt = 0;
int negativeSum = 0;
int negativeCnt = 0;
// Iterate over the numbers taking one of them at a time.
int i = 0;
while (i < integers.size())
{
int number = integers[i];
// Is the number positive?...
if (number >= 0)
{
// ... it is - add it to the positive sum and increment the count.
positiveSum += number;
++positiveCnt;
}
// The number is not positive, so it must be negative...
else
{
// ... add it to the negative sum and increment the count.
negativeSum += number;
++negativeCnt;
}
// Get ready for the next number.
++i;
}
// Time to print out the results.
// Note that before we calculate the average, we have to cast at least one
// of the terms of the division to floating point type. Otherwise the
// division will be done with integers where the result is also an integer
// (e.g. 3 / 2 -> 1).
// Only affter the casting you will be getting expected answers
// (e.g. double(3) / 2 -> 1.5).
std::cout <<
"The (sum, avg) of negative integers = (" <<
negativeSum << ", " <<
double(negativeSum) / negativeCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of positive integers = (" <<
positiveSum << ", " <<
double(positiveSum) / positiveCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of all numbers = (" <<
negativeSum + positiveSum << ", " <<
double(negativeSum + positiveSum) / (negativeCnt + positiveCnt) << ")" << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
char op;
float num1,num2;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
//If the operator is other than +,-,*,/, error message is shown.
cout << "Error! operator is not correct";
break;
}
return 0;
}
#include <iostream>
using namespace std;
int main () {
int input {};
int sum {0};
int tsum {0};
cout << "Number: ";
cin >> input;
for (int i {1}; i <= input; i++) {
for (int j {1}; j <= input; j++) {
sum += j;
tsum += j;
cout << j;
if (j < i) {
cout << "+";
}
}
cout << " = " << tsum << endl;
}
cout << "Your sum is: " << sum << endl;
}
So I found this problem on w3resources for Loop exercises and It wants me to calculate the series so for Example: Lets say my input is 2
it would be output
1 = 1
1 + 2 = 3
The sum of the series is 4
I have been looking at this problem for a week now but cannot wrap my head around it and I even looked at the solution and still do not understand it. Can someone please try to explain it to me because it is very frustrating. I do understand that we need a Nested Loop to get the two numbers to add up but how does sum+=j; and tsum+=j fit in this equation? wouldn't it just be 1+1 = 2 , 1 + 2 = 3 and then 2 + 1 = 3 , and 2 + 2 = 4? How would that get me to my solution????? and how you also fit " = " into play and " + "? and how wouldn't sum and tsum be the same number because they are both adding j to its value?
First, you didn't enter the proposed solution code properly. It is presented here. See how it differs from what you posted (which I have marked with // *** HERE ***:
#include <iostream>
using namespace std;
int main()
{
int i, j, n, sum = 0, tsum;
cout << "\n\n Find the sum of the series (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n):\n";
cout << "------------------------------------------------------------------------------------------\n";
cout << " Input the value for nth term: ";
cin >> n;
for (i = 1; i <= n; i++)
{
tsum = 0;
for (j = 1; j <= i; j++) //*** HERE ***
{
sum += j;
tsum += j;
cout << j;
if (j < i)
{
cout << "+";
}
}
cout << " = " << tsum << endl;
}
cout << " The sum of the above series is: " << sum << endl;
}
Fix that and the exercise makes more sense. That said, the goal of your exercise is to calculate a sum of sums. Given some number natural number n, the algorithm is simply:
sum = 0;
for (i = 1 through n)
for (j = 1 through i)
sum = sum + j;
Suppose the input number was 3. That means you're calculating
(1) + (1+2) + (1+2+3)
Alternative #1 : Regrouping
Note that there are a number of of optimizations you can make to this, based on the recognition of patterns in the sequence above. For example. If you rearrange the number like so:
(1+1+1) + (2+2) + (3)
you can see there are n 1's, (n-1) 2's, etc. up to 1 3's. This pattern holds true for whatever n you deliver. Therefore, you can do this instead:
sum = 0
for (i = 1 through n)
sum = sum + (n - (i-1))*i;
Alternative #2 : Known Sums
A closed form exists for the sum-of-natural-numbers over {1..n}:
sum{1..n} = n*(n+1)/2
Therefore, we can eliminate the inner loop, and simply do this:
sum = 0
for (i = 1 through n)
sum = sum + (i * (i+1))/2;
This, the previous solution, or the two-loop solution, will all deliver the same result. Which you choose is up to you.
Basically I just started doing C++ again after a while because I need to (Degree sorta commands it) and I have been tasked with a simple task of writing a simple program that would take a function and use 2 integer inputs (N and M), returning a double output (S). In one part I am asked to to use a loop to display values for S all the way up to N=10 from N=0 for the value M=10
Ive run into a problem where the return give the value "5" for every N up to 10.
This is the code: (do not mind the comments)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
//Function, Part A
double func_18710726(int N, int M)
{
double S = 0;
for (int n = 1; n <= N; n++)
for (int m = 1; m <= M; m++)
{
S = S + (sqrt(m*n)+exp(sqrt(m))+ exp(sqrt(n)))/(m*n + 2);
}
return S;
}
//Part B
double func_18710726(int, int);
using namespace std;
int main()
{
int N, M;
double S;
//Part B1
do {
cout << "Enter Value of N for N > 0 and an integer" << endl;
cin >> N;
} while (N <= 0);
do {
cout << "Enter value of M for M > 0 and an integer" << endl;
cin >> M;
} while(M <= 0);
//Part B2
S = func_18710726(N, M);
cout << "The Summation is ";
cout << fixed << setprecision(5) << S << endl;
//Part B3
ofstream output;
output.open("Doublesum.txt");
M = 1;
for (int n = 1; n <= 10; n++)
{
S = func_18710726(n, M);
cout << "The summation for N = " << n << " is ";
cout << fixed << setprecision(5) << 5 << endl;
output << fixed << setprecision(5) << 5 << endl;
}
output.close();
return 0;
}
The output gives me:
Enter Value of N for N > 0 and an integer
1
Enter value of M for M > 0 and an integer
2
The Summation is 4.20696
The summation for N = 1 is 5
The summation for N = 2 is 5
The summation for N = 3 is 5
The summation for N = 4 is 5
The summation for N = 5 is 5
The summation for N = 6 is 5
The summation for N = 7 is 5
The summation for N = 8 is 5
The summation for N = 9 is 5
The summation for N = 10 is 5
--------------------------------
Process exited after 2.971 seconds with return value 0
Press any key to continue . . .
Any help as to why this is happening is much appreciated.
The Question itself
I am sorry if I posted this in the wrong place, if I do, Mods please go easy on me :)
This line:
cout << fixed << setprecision(5) << 5 << endl;
has 5 (five) as its output - you want S (esss)
Probably S is not such a great name for a variable (neither is l)
You may have heard of a website called Project Euler (projecteuler.net). I'm working through the first problems, which were quite trivial, and I'm on the problem described in the title.
This isn't about optimising or anything - it takes about 90 thousandths of a second to complete. It's giving me the wrong total.
Can someone help me? I have no clue why the answer I'm getting - from both the array total (atotal) and the total that was added up normally (total) - is incorrect. The answer they are both showing is 947402457, which the website it telling me is the wrong answer.
In case it's just the wording, the question is here: http://projecteuler.net/index.php?section=problems&id=10
What's also very strange is, as far as I can tell, when, at the end when you can type in which prime number you would like to view (it takes it out of the array), it gives you the correct answer.
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <ctime>
typedef unsigned long int bignum;
//there are 666671 primes below two million
int main(){
using namespace std;
bignum top = 2000000;
bignum total = 0;
bignum atotal = 0;
//hardcode 2 and 3
total += 5;
int inc = 2;
bignum n = 5;
double sq = n;
bignum np = 1;
bignum *pa = new bignum[top];
pa[0] = 2;
pa[1] = 3;
while (n < top){
int div = 5;
int divinc = 2;
int p = 1;
//check if number is prime
//check divisiblity from any possible prime up to the square root of n
//first hardcode 2 and 3
if(n%2==0||n%3==0)
p = 0;
else{
while(div<=sqrt(sq)){
if(n%div==0){
p = 0;
break;
}else{
div = div + divinc;
if(divinc==2) divinc = 4; else divinc = 2;
}
}if(p!=0){ //if it's a prime - 0 is not, 1 is prime
total = total + n;
np++;
pa[np] = n;
//cout << np << " prime number: " << n << endl; //takes too long if it prints everything
}
}
n += inc;
if(inc==2) inc = 4; else inc = 2;
}
for (int c=0;c<=np;c++){
atotal += pa[c];
}
cout << "Total " << top << ": " << total << endl;
cout << "Array total: " << atotal << endl;
cout << "Elapsed time: " << clock() << " " << CLOCKS_PER_SEC << "s of a second" << endl << endl;
while(true){
int ptoview = 0;
cout << "Enter the number of the prime you would like to see (you can view every prime number below "<<top<<") ";
cin >> ptoview;
if (pa[ptoview-1]){
if (pa[ptoview-1] < top)
cout << ptoview << " prime: " << pa[ptoview-1] << endl;
else
cout << "Too high/low" << endl;
cout << endl;
}
}
system("PAUSE");
return 0;
}
Here's a clue to at least one problem. Have a look at what happens when you replace:
for (int c=0;c<=np;c++){
atotal += pa[c];
}
with:
for (int c=0;c<=np;c++){
bignum oldatotal = atotal;
atotal += pa[c];
if (atotal < oldatotal)
cout << "Hmmm: " << oldatotal << " " << atotal << endl;
}
I get something like:
Hmmm: 4294819625 12858
Hmmm: 4294864122 123849
Hmmm: 4294717053 27802
Hmmm: 4294697657 51420
: : :
Hmmm: 4293781002 792849
Hmmm: 4294658253 1676602
Hmmm: 4293686116 710941
Hmmm: 4294706293 1737578
Total 2000000: 947402457
Array total: 947402457
I won't go into the detail since this is a puzzle and I'm assuming you want to keep it at least a little challenging :-)
And yes, you're right (based on your comment below) so I'll make the answer a little less obtuse so it's more useful for others.
The unsigned long type is not big enough to hold the sum of all those primes so it's wrapping around.
Whether it can hold the actual primes themselves I haven't checked, but the answer in the next paragraph will solve that as well.
You might want to try redefining bignum as a "larger" type like unsigned long long if available.
Not looked at everything but sq isn't modified in the main while loop. That doesn't seem right. (BTW, I'd have used a sieve filter to get to the primes).