am running these two functions that do the same calculation "summing the first N integers " then compare the run times for each one. The program works fine with small inputs, but the problem is when I input large numbers like 1000000, it calculates the first method "the iterativeSum()" then as soon as it gets to the the recursiveSum() it stops working.
am not sure but do you think that this might be because of the cout?
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void iterativeSum(int);
int RecursiveSum(int);
int main()
{
long long posInt;
std::cout << "Enter a positive integer: ";
std::cin >> posInt;
int start_s=clock();
iterativeSum(posInt);
int stop_s=clock();
int start_s1=clock();
cout << "\nThe recursive algorithm to sum the first N integers of "<< posInt << " is: "<< RecursiveSum(posInt) << endl;
int stop_s1=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)/1000 << endl;
cout << "time: " << (stop_s1-start_s1)/double(CLOCKS_PER_SEC)/1000 << endl;
return 0;
}
void iterativeSum(int posInt)
{
//positive Integer >=0
int sum = 0;
//loop through and get only postive integers and sum them up.
// postcondion met at i = 0
for(int i = 0; i <= posInt;i++)
{
sum +=i;
}
//output the positive integers to the screen
std::cout <<"\nThe iterative algorithm to sum the first N integers of " <<posInt <<" is: " << sum << "\n";
}
int RecursiveSum(int n)
{
if(n == 1) // base case
{
return 1;
}
else
{
return n + RecursiveSum(n - 1); //This is n + (n - 1) + (n - 2) ....
}
}
You may need an arbitrary precision arithmetic library like GMPlib, to avoid arithmetic overflows. And you should be afraid of stack overflow.
The call stack is often limited (to e.g. a megabyte). See this
Related
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;
}
I started to learn C++ and my homework is to write a code where you can enter 5 numbers and the program will tell you for each number whether it is a Fibonacci number or not.
I also tried using a do/while-loop in the isFibonacci function instead of the for-loop, but that did not fix the problem.
#include <iostream>
#include <cstdio>
using namespace std;
//function to test whether a number is a Fibonacci number or not
bool isFibonacci (int i)
{
//special cases with 0 and 1:
if ( i == 0 || i ==1) {
return true;
}
//for all other numbers:
int Fib1;
int Fib2;
int Fib3;
for (Fib3=0; Fib3>=i; Fib3++) {
Fib3 = Fib1 + Fib2;
Fib1 = Fib2;
Fib2 = Fib3;
if (Fib3==i){
return true;
}
else {
return false;
}
}
}
int main ()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
cout << "Please enter 5 numbers;" << endl;
cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i=0; i<5; i++) {
result=isFibonacci (numbers[i]);
if (result == true) {
cout << "Your number " << numbers[i] << " is a Fibonacci number!" << endl;
}
else {
cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << endl;
}
}
return 0;
}
The first Fibonacci numbers are (0),1,1,2,3,5,8,12.
So when I enter 5 numbers, for example 1,2,3,4,5 I should get a "yes" for 1,2,3 and 5, but a "no" for 4.
However, my program claims that except for 1, none of these numbers are Fibonacci numbers.
Basically your approach was a good idea. But you made some implementation errors in your check function. Like not initialized variables and wrong calculations. And look at you for loop.
Additionally. There will be a problem with big numbers.
Many very smart people, explored the Fibonacci numbers. There are whole books available. Also a Wikipedia article. See here.
Or look into that book:
The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
Or also here on stackoverflow
Therefore I will not reinvent the wheel. Here is your revised software:
#include <iostream>
#include <cmath>
#include <numeric>
// Positive integer ? is a Fibonacci number
// If and only if one of 5?2 + 4 and 5?2 - 4 is a perfect square
// from The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
// Function to test whether a number is a Fibonacci number or not
bool isFibonacci(int w)
{
{
double x1 = 5 * std::pow(w, 2) + 4;
double x2 = 5 * std::pow(w, 2) - 4;
long x1_sqrt = static_cast<long>(std::sqrt(x1));
long x2_sqrt = static_cast<long>(std::sqrt(x2));
return (x1_sqrt * x1_sqrt == x1) || (x2_sqrt * x2_sqrt == x2);
}
}
int main()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
std::cout << "Please enter 5 numbers;" << std::endl;
std::cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i = 0; i < 5; i++) {
result = isFibonacci(numbers[i]);
if (result == true) {
std::cout << "Your number " << numbers[i] << " is a Fibonacci number!" << std::endl;
}
else {
std::cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << std::endl;
}
}
return 0;
}
this code finds the binary of a decimal integer N; it divides the number by 2 and takes the floor of the result and divides it also by 2,
the code gets the remainder of those divisions 0 or 1 and builds up the binary.
The problem with this code is that it won't run until the last division example (take 128 the last division is 1/2 and remainder is 1, the program stops at N/2 > 0 as specified in the while loop and 1/2 = 0 since 1 is of type int).
How do I resolve this issue or how do I modify the condition in the while loop?
#include <iostream>
using namespace std;
void ConvertToBinary(int N);
int main()
{
int N = 1;
while (1)
{
cout << "enter N: ";
cin >> N;
cout << endl;
ConvertToBinary(N);
cout << endl;
}
system("pause");
return 0;
}
void ConvertToBinary(int N)
{
int A[1000];
int i=0;
cout << "The binary of " << N << "= ";
while (N / 2 > 0)
{
if (N % 2 == 0)
{
A[i] = 0;
}
else if (N % 2 != 0)
{
A[i] = 1;
}
N = N / 2;
i++;
}
for (int j= i-1 ; j>=0 ; j--)
{
cout<<A[j];
}
cout << endl;
}
N is not "a decimal integer". It is a number.
If you really want to talk specifics, it's already stored in binary.
What you're talking about is representation. What is the representation of the number when printed to screen? IOStreams by default will show you numbers in decimal.
You can use I/O Manipulators, though, to choose hexadecimal or octal instead. Sadly there isn't a std::bin yet, but we can use std::bitset for the same purpose:
#include <iostream>
#include <iomanip>
#include <bitset>
int main()
{
int x = 42;
std::cout << x << '\n';
std::cout << std::hex << x << '\n';
std::cout << std::oct << x << '\n';
std::cout << std::bitset<sizeof(x)>(x) << '\n';
}
// Output:
// 42
// 2a
// 52
// 1010
(live demo)
And your whole approach (to "fake" a representation shift by changing your number to another number that happens to look like the binary representation of the original number when you print it in decimal representation — phew!) becomes obsolete, solving your problem effortlessly.
I'm learning C++ and am trying create a program to find the factorial of a positive integer. I've been able to find the factorial of a positive integer. However, I am still trying to have the program give an error message when the input is not a positive integer. So far, the error message has been combined with the standard output message.
How do I construct loops such that the factorial of the given positive integer is found for a positive integer input, while providing only an error message when the input is not a positive integer? Code is below. Thank you.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i;
int n;
int factorial;
factorial = 1;
cout << "Enter a positive integer. This application will find its factorial." << '\n';
cin >> i;
if (i < 1)
{
cout << "Please enter a positive integer" << endl;
break;
}
else
for (n = 1; n <= i; ++n)
{
factorial *= n;
}
cout << " Factorial " << i << " is " << factorial << endl;
return 0;
}
I did not check if your factorial function returns the correct results. Also, you may wish to make it recursive, :)
Add braces for your else:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i;
int n;
int factorial;
factorial = 1;
cout << "Enter a positive integer. This application will find its factorial." << '\n';
cin >> i;
if (i < 1)
{
cout << "Please enter a positive integer" << endl;
break;
}
else {
for (n = 1; n <= i; ++n)
{
factorial *= n;
}
cout << " Factorial " << i << " is " << factorial << endl;
}
return 0;
}
There is a complete factorial of number program of c++ which handles positive, negative numbers and also zero.
#include<iostream>
using namespace std;
i
nt main()
{
int number,factorial=1;
cout<<"Enter Number to find its Factorial: ";
cin>>number;
if(number<0)
{
cout<<"Not Defined.";
}
else if (number==0)
{
cout<<"The Facorial of 0 is 1.";
}
else
{
for(int i=1;i<=number;i++)
{
factorial=factorial*i;
}
cout<<"The Facorial of "<<number<<" is "<<factorial<<endl;
}
return 0;
}
You can read complete code explanation on http://www.cppbeginner.com/numbers/how-to-find-factorial-of-number-in-cpp/
So I wrote a program that utilizes the euclid algorithm to find GCD's of 2 ints.
The user enters one int (n), then the program takes every possible integer combination between 8 and n, finds their respective GCD's (recursively), and prints which GCD calculations required the most modulus operations.
I got the program working, but I get a stack overflow at around n=50, and it needs to work to at least 3000.
I've reviewed my code for a while and cannot find the problem.
#include<iostream>
#include <math.h>
using namespace std;
int cost, gcd, greatestCost, n, beginningA, beginningB, finalA, finalB, finalGCD, iteration;
void findGCD(int num1, int num2, int startingCost) {
//findGCD
//finds GCD of every combination (a,b) from i to n
//prints those with the greatest number of modulus operations
int a = num1;
int b = num2;
cost = startingCost;
cost++;
if (b%a > 0) {
//cout << "gcd(" << b << "," << a << ") = ";
findGCD(b%a, a, cost);
}
else {
gcd = a;
if (cost > greatestCost) {
greatestCost = cost;
finalA = beginningA;
finalB = beginningB;
finalGCD = gcd;
}
//cout << "gcd(" << b << "," << a << ") = " << gcd << " With a cost of: " << cost << endl;
//do next iteration (2,8), (3,8) etc...
if (++beginningA <= beginningB) { //beginning A goes from 1-i first
findGCD(beginningA, beginningB, 0);
}
else {
if (beginningA <= n) { //begin next cycle with new b value (1,9), (2,9) while b <= n
beginningA = 1; //reset to 1 so it will increment from 1-i again
cout << "At i=" << iteration++ << "; gcd(" << finalA << "," << finalB << ") = " << finalGCD <<
" took " << greatestCost << " modulus operations" << endl;
findGCD(beginningA, ++beginningB, 0);
}
else //When it tries to continue iterating with a number > n
//print the last, most intensive, iteration and stop
cout << "At i=" << iteration++ << "; gcd(" << finalA << "," << finalB << ") = " << finalGCD <<
" took " << greatestCost << " modulus operations" << endl;
}
}
}
int main() {
greatestCost = 0; //cost of the iteration with the most modulus operations
beginningA = 1;
beginningB = 8;
iteration = 8;
cout << "Enter an integer greater than 8 " << endl; //receive n from user
cin >> n;
if (n <= beginningB) //begin GCD search, granted user input > 8
cout << "Error!!! integer must be greater than 8";
else
findGCD(beginningA, beginningB, 0); //algorithm begins at (1,8)
return 0;
}
At this point the only thing I can think of as the problem is something I've done in C++ that I shouldn't (I am new to C++ and transferred over from java)
Sample Output
Things I've tried:
splitting the gcd function into 2
passing only references through the functions
First of all your explanation is unclear, from you code I understood that for every 8<=i<=n you take all possible x, y where y<=i and x<=y and calculate which gcd require most steps.
I've rewritten your code so that findGCD only finds gcd of 2 number, while incrementing some global cost variable.
#include<iostream>
#include <math.h>
using namespace std;
int cost, gcd, greatestCost, n, beginningA, beginningB, finalA, finalB, finalGCD, iteration;
int findGCD(int a, int b) {
cost++;
if (b%a > 0)
return findGCD(b%a, a);
else
return a;
}
int main() {
greatestCost = 0; //cost of the iteration with the most modulus operations
beginningA = 1;
beginningB = 8;
iteration = 8;
cout << "Enter an integer greater than 8 " << endl; //receive n from user
cin >> n;
if (n <= beginningB) //begin GCD search, granted user input > 8
cout << "Error!!! integer must be greater than 8";
else {
for ( int i = beginningB; i <= n; i++ ) {
int greatestCost = 0, gcd0 = 1, i0 = 0, j0 = 0;
for ( int t = beginningB; t <= i; t++ )
for ( int j = 1; j <= t; j++ ) {
cost = 0;
int gcd = findGCD(j, t);
if ( cost > greatestCost ) {
greatestCost = cost;
gcd0 = gcd;
i0 = t;
j0 = j;
}
}
cout << "At i=" << i << "; gcd(" << j0 << "," << i0 << ") = " << gcd0 <<
" took " << greatestCost << " modulus operations" << endl;
}
}
return 0;
}
The stack overflow you're getting is caused by using too deeply recursive calls: Every time you call a function a new stack frame (holding local variables, parameters and possibly other stuff) is created in the (call) stack. This frame is freed only when returning (normally or via exception) from the function. But with recursive calls you don't return from the first function call before returning from the second, which in turn only returns after the third and so on. Thus stack frames are piling up on the stack, which is commonly about the size of around 8 kB, until all available memory for the stack is used: That's the stack overflow (you put too much on it, thus it overflows).
This can be solved by using iteration (using loops) instead:
An outer one incrementing from 8 up to the user supplied maximum, as well as an inner one incrementing from 0 to the value of the outer loop's current iteration variable. This gives you all the pairs of values you want to operate on.
Calculating the greatest common divisor and its cost should be factored out into a function.
The only thing left is calling that function from within the loops and some how keeping track of the maximum.
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
unsigned gcd(unsigned a, unsigned b, unsigned * const cost) {
if (cost) {
*cost = 0;
}
while (b != 0) {
auto const rest = a % b;
if (cost) {
++(*cost);
}
a = b;
b = rest;
}
return a;
}
int main() {
unsigned const n = 3500;
unsigned greatestCost = 0;
vector<pair<unsigned, unsigned>> pairs;
for (unsigned b = 8; b <= n; ++b) {
for (unsigned a = 0; a <= b; ++a) {
unsigned cost;
gcd(a, b, &cost);
if (cost == greatestCost) {
pairs.emplace_back(a, b);
} else if (cost > greatestCost) {
pairs.clear();
pairs.emplace_back(a, b);
greatestCost = cost;
}
}
}
cout << "Greatest cost is " << greatestCost << " when calculating the GCD of " << endl;
for (auto const & p : pairs) {
cout << "(" << p.first << ", " << p.second << ")" << endl;
}
return 0;
}
(Live)
Note in particular that I'm not using any global variable.
The above might make you feel that recursion is an unusable, useless construct. This is not the case. Many algorithms are most cleanly expressed using recursion. When putting the recursive call as the last statement, then an optimisation known as tail call optimisation can be used: Then the called function is reusing the stack frame of the calling function, thus not using any more memory.
Unfortunately this optimisation is quite tricky to implement in a language like C++ due to various reasons.
Other languages, mostly functional ones, use it and thus also recursion instead of loops, though. An example of such a language is Scheme, which even requires implementations to be able to make that aforementioned optimisation.
As a final note: You could implement the GCD calculation using recursive calls here, since as you see the maximum depth will be 17 + 1 which should be small enough to fit on any (outside of embedded systems) call stack. I'd still go with the iterative version though: It has better performance, better fits the idiom of the language and is the "safer" way to go.