Dynamic numerical series - c++

I am trying to create a program to print first 200 elements following a specific numerical series condition which is
1-1-3-6-8-8-10-20
But instead of showing, just 200 elements is showing 802. I assume is because of the code inside the for loop. I have hours thinking on how to reduce that code to the job and I cannot think anything else. I am getting frustrated and need your help.
The exercise is on the code comments
//Print the following numerical series 1-1-3-6-8-8-10-20 until 200
#include <stdafx.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Num1=200, z = 0, x = 1, y = 1;
cout << "\n\n1,";
cout << " 1,";
for (int i = 1; i <= Num1; i++)
{
z = y + 2;
cout << " " << z << ","; //It will print 3
z = z * 2;
cout << " " << z << ",";//It will print 6
z = z + 2;
cout << " " << z << ",";//It will print 8
z = z;
cout << " " << z << ",";//It will print 8
y = z;
}
cout << "\n\n";
system("pause");
return 0;
}

You're looping 200 times, and each time you loop, you're printing out 4 different numbers. You're also printing twice at the start so thats 2 + 4 * 200 = 802, which is where your 802 number output is coming from.

I assume is because of the code inside the "for" loop but I've hours
thinking on how to reduce that code to the job and I cannot think
anything else. I'm getting frustrated and need your help.
So you basically wanna simplify your code. Which can be done by noticing the repetitions.
There you can find only two types of change in the series; either a +2 or x2 with the previous element.
In each iteration this can be achieved by:
If reminder i%4 == 1 or i%4 == 3, need an increment of 2 (assuming 1 <= i <= MAX)
If reminder i%4 == 0, nothing but a multiplication of 2.
When you do like so, you can simply neglect, printing of first two ones and other complications in the total numbers in the series.
Also not that, you are trying to get 200 terms of this series, which increases in each step very fast and exceed the maximum limit of int. Therefore, long long is needed to be used instead.
The updated code will look like this:
#include <iostream>
typedef long long int int64;
int main()
{
int size = 200;
int64 z = -1;
for (int i = 1; i <= size; i++)
{
if ((i % 4 == 1) || (i % 4 == 3)) z += 2;
else if (i % 4 == 0) z *= 2;
std::cout << z << "\n";
}
return 0;
}
See the Output here: https://www.ideone.com/JiWB8W

Related

How can I make this C++ code shorter? (Coin Change Calculator)

I'm a C++ beginner. I just made a coin change calculator and now I want the code to be shorter (with a loop or something). How can I do that?
#include <iostream>
int main() {
int amount = 0;
int result[4] = { 0, 0, 0, 0 };
int values[4] = { 25, 10, 5, 1 };
int x = 0;
std::cout << "Welcome to this super advanced (not) coin change calculator! \n";
std::cout << "Please enter the amount in cents: ";
std::cin >> amount;
x = amount;
result[0] = x / values[0];
x = x % values[0];
result[1] = x / values[1];
x = x % values[1];
result[2] = x / values[2];
x = x % values[2];
result[3] = x / values[3];
x = x % values[3];
std::cout << "Optimal change: " << result[0] << " quarter(s), " << result[1] << " dime(s), " << result[2] << " nickel(s), and " << result[3] << " pennie(s)!";
return 0;
}
A few techniques apply
1) Rather than outputting multiple string literals to std::cout, combine all the literals into one, and output that. Bear in mind that a pair of string literals following each other are combined. For example, the construct "ab" "cd" becomes "abcd"
2) Eliminate any variables that are not needed. In your case, your code reads to amount, does an assignment x = amount, and then never uses amount again. This means there is an opportunity to eliminate either amount (read directly to x and proceed from there) or x (don't assign x = amount, and then do all operations on amount).
3) If you are reusing logic that only differs by an index such as result[0] = x/values[0] and later result[1] = x/values[1] then consider a loop.
4) If you have multiple strings to be output (you do!) consider placing them in an array too - then access elements of that array if the loops too.
5) Don't be afraid to break statements into pieces and re-order operations if it allows you to rationalise.
6) If we are doing x = x op y change that to x op = y. For example, change amount = amount % values[i] to amount %= values[i].
Putting all that together, you get.
#include <iostream>
int main()
{
int amount = 0;
int result[4] = { 0, 0, 0, 0 };
int values[4] = { 25, 10, 5, 1 };
const char *denom[4] = {"quarter(s),",
"dime(s),",
"nickel(s), and",
"pennie(s)!"
};
std::cout << "Welcome to this super advanced (not) coin change calculator!\n"
"Please enter the amount in cents: ";
std::cin >> amount;
for (i = 0; i < 4; ++i)
{
result[i] = amount / values[i];
amount %= values[i];
}
std::cout << "Optimal change: ";
for (i = 0; i < 4; ++i)
{
std::cout << result[i] << denom[i] << " ";
}
return 0;
}
But we can go further. In the above, I've broken the initialisation of denom into multiple lines for clarity, but the initialisation of the array can be combined into a single line (at some cost of readability)
const char *denom[4] = {"quarter(s),", "dime(s),", "nickel(s), and", "pennie(s)!"};
Having done this, we see that can combine the two loops into one if we move the output statement that is between them, and then not actually need the array result (elements are only calculated in the loop, and then output). So we can eliminate that array, and make it a single variable - local to the loop.
std::cout << "Optimal change: ";
for (int i = 0; i < 4; ++i)
{
int result = amount / values[i];
amount %= values[i];
std::cout << result << denom[i] << " ";
}
return 0;
}
Having done that, look inside the loop, and note that result is only calculated so we can output it. So eliminate it by changing the loop to
for (int i = 0; i < 4; ++i)
{
std::cout << amount/values[i] << denom[i] << " ";
amount %= values[i];
}
Having done all that, we get
#include <iostream>
int main()
{
int amount = 0;
int values[4] = { 25, 10, 5, 1 };
const char *denom[4] = {"quarter(s),", "dime(s),", "nickel(s), and", "pennie(s)!"};
std::cout << "Welcome to this super advanced (not) coin change calculator!\n"
"Please enter the amount in cents: ";
std::cin >> amount;
std::cout << "Optimal change: ";
for (int i = 0; i < 4; ++i)
{
std::cout << amount/values[i] << denom[i] << " ";
amount %= values[i];
}
return 0;
}
In doing the above, I've focused on making your code shorter. I have taken liberties with changing the order in which operations are done, but the output produced will be the same.
There is more that can be done too. Your code is fairly straight forward, but the C++ standard library includes containers (to manage collections of values) that represent vectors, lists, strings, etc. These allow you to eliminate raw pointers or raw arrays entirely, and operations (like resizing, inserting elements, removing elements, etc) are handled more cleanly than doing them by hand. There is also a set of algorithms (in standard header <algorithm>) that can operate on every element of containers - if you are writing loops that run over every element of a container (or even a raw array), then there is often (not always) an algorithm that can be used to do the same thing - with more concise code that is easier to read, therefore easier to get right.

Program only works with inclusion of (side effects free) cout statements?

So I've been working on problem 15 from the Project Euler's website , and my solution was working great up until I decided to remove the cout statements I was using for debugging while writing the code. My solution works by generating Pascal's Triangle in a 1D array and finding the element that corresponds to the number of paths in the NxN lattice specified by the user. Here is my program:
#include <iostream>
using namespace std;
//Returns sum of first n natural numbers
int sumOfNaturals(const int n)
{
int sum = 0;
for (int i = 0; i <= n; i++)
{
sum += i;
}
return sum;
}
void latticePascal(const int x, const int y, int &size)
{
int numRows = 0;
int sum = sumOfNaturals(x + y + 1);
numRows = x + y + 1;
//Create array of size (sum of first x + y + 1 natural numbers) to hold all elements in P's T
unsigned long long *pascalsTriangle = new unsigned long long[sum];
size = sum;
//Initialize all elements to 0
for (int i = 0; i < sum; i++)
{
pascalsTriangle[i] = 0;
}
//Initialize top of P's T to 1
pascalsTriangle[0] = 1;
cout << "row 1:\n" << "pascalsTriangle[0] = " << 1 << "\n\n"; // <--------------------------------------------------------------------------------
//Iterate once for each row of P's T that is going to be generated
for (int i = 1; i <= numRows; i++)
{
int counter = 0;
//Initialize end of current row of P's T to 1
pascalsTriangle[sumOfNaturals(i + 1) - 1] = 1;
cout << "row " << i + 1 << endl; // <--------------------------------------------------------------------------------------------------------
//Iterate once for each element of current row of P's T
for (int j = sumOfNaturals(i); j < sumOfNaturals(i + 1); j++)
{
//Current element of P's T is not one of the row's ending 1s
if (j != sumOfNaturals(i) && j != (sumOfNaturals(i + 1)) - 1)
{
pascalsTriangle[j] = pascalsTriangle[sumOfNaturals(i - 1) + counter] + pascalsTriangle[sumOfNaturals(i - 1) + counter + 1];
cout << "pascalsTriangle[" << j << "] = " << pascalsTriangle[j] << '\n'; // <--------------------------------------------------------
counter++;
}
//Current element of P's T is one of the row's ending 1s
else
{
pascalsTriangle[j] = 1;
cout << "pascalsTriangle[" << j << "] = " << pascalsTriangle[j] << '\n'; // <---------------------------------------------------------
}
}
cout << endl;
}
cout << "Number of SE paths in a " << x << "x" << y << " lattice: " << pascalsTriangle[sumOfNaturals(x + y) + (((sumOfNaturals(x + y + 1) - 1) - sumOfNaturals(x + y)) / 2)] << endl;
delete[] pascalsTriangle;
return;
}
int main()
{
int size = 0, dim1 = 0, dim2 = 0;
cout << "Enter dimension 1 for lattice grid: ";
cin >> dim1;
cout << "Enter dimension 2 for lattice grid: ";
cin >> dim2;
latticePascal(dim1, dim2, size);
return 0;
}
The cout statements that seem to be saving my program are marked with commented arrows. It seems to work as long as any of these lines are included. If all of these statements are removed, then the program will print: "Number of SE paths in a " and then hang for a couple of seconds before terminating without printing the answer. I want this program to be as clean as possible and to simply output the answer without having to print the entire contents of the triangle, so it is not working as intended in its current state.
There's a good chance that either the expression to calculate the array index or the one to calculate the array size for allocation causes undefined behaviour, for example, a stack overflow.
Because the visibility of this undefined behaviour to you is not defined the program can work as you intended or it can do something else - which could explain why it works with one compiler but not another.
You could use a vector with vector::resize() and vector::at() instead of an array with new and [] to get some improved information in the case that the program aborts before writing or flushing all of its output due to an invalid memory access.
If the problem is due to an invalid index being used then vector::at() will raise an exception which you won't catch and many debuggers will stop when they find this pair of factors together and they'll help you to inspect the point in the program where the problem occurred and key facts like which index you were trying to access and the contents of the variables.
They'll typically show you more "stack frames" than you expect but some are internal details of how the system manages uncaught exceptions and you should expect that the debugger helps you to find the stack frame relevant to your problem evolving so you can inspect the context of that one.
Your program works well with g++ on Linux:
$ g++ -o main pascal.cpp
$ ./main
Enter dimension 1 for lattice grid: 3
Enter dimension 2 for lattice grid: 4
Number of SE paths in a 3x4 lattice: 35
There's got to be something else since your cout statements have no side effects.
Here's an idea on how to debug this: open 2 visual studio instances, one will have the version without the cout statements, and the other one will have the version with them. Simply do a step by step debug to find the first difference between them. My guess is that you will realize that the cout statements have nothing to do with the error.

C++ Long Division

Whilst working on a personal project of mine, I came across a need to divide two very large arbitrary numbers (each number having roughly 100 digits).
So i wrote out the very basic code for division (i.e., answer = a/b, where a and b are imputed by the user)and quickly discovered that it only has a precision of 16 digits! It may be obvious at this point that Im not a coder!
So i searched the internet and found a code that, as far as i can tell, uses the traditional method of long division by making a string(but too be honest im not sure as im quite confused by it). But upon running the code it gives out some incorrect answers and wont work at all if a>b.
Im not even sure if there's a better way to solve this problem than the method in the code below!? Maybe there's a simpler code??
So basically i need help to write a code, in C++, to divide two very large numbers.
Any help or suggestions are greatly appreciated!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std; //avoids having to use std:: with cout/cin
int main (int argc, char **argv)
{
string dividend, divisor, difference, a, b, s, tempstring = ""; // a and b used to store dividend and divisor.
int quotient, inta, intb, diff, tempint = 0;
char d;
quotient = 0;
cout << "Enter the dividend? "; //larger number (on top)
cin >> a;
cout << "Enter the divisor? "; //smaller number (on bottom)
cin >> b;
//making the strings the same length by adding 0's to the beggining of string.
while (a.length() < b.length()) a = '0'+a; // a has less digits than b add 0's
while (b.length() < a.length()) b = '0'+b; // b has less digits than a add 0's
inta = a[0]-'0'; // getting first digit in both strings
intb = b[0]-'0';
//if a<b print remainder out (a) and return 0
if (inta < intb)
{
cout << "Quotient: 0 " << endl << "Remainder: " << a << endl;
}
else
{
a = '0'+a;
b = '0'+b;
diff = intb;
//s = b;
// while ( s >= b )
do
{
for (int i = a.length()-1; i>=0; i--) // do subtraction until end of string
{
inta = a[i]-'0'; // converting ascii to int, used for munipulation
intb = b[i]-'0';
if (inta < intb) // borrow if needed
{
a[i-1]--; //borrow from next digit
a[i] += 10;
}
diff = a[i] - b[i];
char d = diff+'0';
s = d + s; //this + is appending two strings, not performing addition.
}
quotient++;
a = s;
// strcpy (a, s);
}
while (s >= b); // fails after dividing 3 x's
cout << "s string: " << s << endl;
cout << "a string: " << a << endl;
cout << "Quotient: " << quotient << endl;
//cout << "Remainder: " << s << endl;
}
system ("pause");
return 0;
cin.get(); // allows the user to enter variable without instantly ending the program
cin.get(); // allows the user to enter variable without instantly ending the program
}
There are much better methods than that. This subtractive method is arbitrarily slow for large dividends and small divisors. The canonical method is given as Algorithm D in Knuth, D.E., The Art of Computer Programming, volume 2, but I'm sure you will find it online. I'd be astonished if it wasn't in Wikipedia somewhere.

C++ Pi Estimating Program Not Working Correctly

I am currently writing a program that estimates Pi values using three different formulas pictured here: http://i.imgur.com/LkSdzXm.png .
This is my program so far:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double leibniz = 0.0; // pi value calculated from Leibniz
double counter = 0.0; // starting value
double eulerall = 0.0; // pi value calculated from Euler (all integers)
double eulerodd = 0.0; // value calculated from Euler (odds)
int terms;
bool negatives = false;
cin >> terms;
cout << fixed << setprecision(12); // set digits after decimal to 12 \
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++;
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++;
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++;
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
if (terms < 0){
if(!negatives)
negatives=true;
cout << "There were " << negatives << " negative values read" << endl;
}
return 0;
}
The sample input file that I am using is:
1
6
-5
100
-1000000
0
And the sample output for this input file is:
1 4.000000000000 2.449489742783 3.174802103936
6 2.976046176046 2.991376494748 3.141291949057
100 3.131592903559 3.132076531809 3.141592586052
When I run my program all I get as an output is:
1 4.000000000000 1.224744871392 1.131370849898.
So as you can see my first problem is that the second and third of my equations are wrong and I can't figure out why. My second problem is that the program only reads the first input value and stops there. I was hoping you guys could help me figure this out. Help is greatly appreciated.
You have three problems:
First, you do not implement the Euler formulae correctly.
π2/6 = 1/12 + 1/22 + 1/32 + ...
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
The square root of the sum is not the sum of the square roots.
π3/32 = 1/13 + 1/33 + 1/53 + ...
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
This is just... wrong.
Second, you increment counter three times in the loop, instead of once:
while(terms > counter){
...
counter++;
...
counter++;
...
counter++;
...
}
Third, and most fundamental, you didn't follow the basic rule of software development: start small and simple, add complexity as little at a time, test at every step, and never add to code that doesn't work.
my first problem is that the second and third of my equations are
wrong and I can't figure out why
Use counter++ just once. Apart from this Leibniz looks fine.
Eulerall is not correct, you should sum all factors and then do sqrt and multiplication at the end:
eulerall = 1/pow(counter+1,2) + eulerall;
// do sqrt and multiplication at the end to get Pi
The similar thing with eulerodd: you should sum all factors and then do sqrt and multiplication at the end.
My second problem is that the program only reads the first input value
and stops there.
In fact this is your first problem. This is because you are incrementing counter multiple times:
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++; // << increment
^^^^^^^^^^
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++; // << increment
^^^^^^^^^^
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++; // << increment
^^^^^^^^^^
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
You should increment counter just once.
You're using the same counter and incrementing it after each calculation. So each technique is only accounting for every third term. You should increment counter only once, at the end of the loop.
Also note that it is generally bad form to use a floating-point value as a loop counter. It only takes on integer values in your program, so you can just make it an int. Nothing else needs to change; the math will run the same because the int will promote to a double when you combine the two in math operations.
#include<iostream>
#include<conio.h>
#include<cmath>
using namespace std;
char* main()
{
while(1)
{
int Precision;
float answer = 0;
cout<<"Enter your desired precision to find pi number : ";
cin>>Precision;
for(int i = 1;i <= Precision;++i)
{
int sign = (pow((-1),static_cast<float>(i + 1)));
answer += sign * 4 * ( 1 / float( 2 * i - 1));
}
cout<<"Your answer is equal to : "<<answer<<endl;
_getch();
_flushall();
system("cls");
}
return "That is f...";
}

C++ Random Number Generator For Loop

So, I have a small problem here with a rather large for loop. This program is to simulate random walks of 100 steps each - what I want to do is have the program perform 1 million of these random walk simulations (the random walk is done by the nested for loop essentially by simulating the flipping of a coin, as you can see in my code below) and take the resultant displacement from each of these random walks and print them to the console window and to the specified output file.
However, my code seems to be adding each final value of x from the nested for loop and then printing them to the console window (and saving to output file) - I don't want this, I just want the standalone net result from each random walk to be outputted for each value of j (which ranges from 1 to 1E6 as specified by the outer for loop).
Thus, any help would be greatly appreciated. Also, I would very much appreciate you to not just quote some code for me to use instead but rather explain to me where my program logic has gone wrong and why.
Thanks in advance, my code is below!
#include <iostream>
#include <ctime>
#include <fstream>
using namespace std;
int main(void) {
const unsigned IM = 1664525;
const unsigned IC = 1013904223;
const double zscale = 1.0/0xFFFFFFFF; //Scaling factor for random double between 0 and 1
unsigned iran = time(0); //Seeds the random-number generator from the system time
const int nsteps(100); //Number of steps
const int nwalks(1E6);
int x(0); // Variable to count step forward/back
ofstream randout;
randout.open("randomwalkdata2.txt");
// Table headers for console window and output file
cout << "Random Walk Number \t Resultant Displacement \n";
randout << "Random Walk Number \t Resultant Displacement \n";
for ( int j = 1 ; j <= nwalks ; j++ ) {
for ( int i = 1 ; i <= nsteps ; i++ ) {
// if-else statement to increment/decrement x based on RNG
if ( zscale * double( iran = IM * iran + IC ) < 0.5 ) //RNG algorithm
x++;
else
x--;
}
cout << j << "\t" << x << endl;
randout << j << "\t" << x << endl;
}
randout.close();
return 1;
}
You forgot to re-initialize x after each random walk.
cout << j << "\t" << x << endl;
randout << j << "\t" << x << endl;
x=0;
Should do the trick.