Sum finder not consistent - c++

My code here finds the sum of some given multiples less than or equal to a certain number. It uses a modified version of a formula I read about on the internet a while ago (the one for finding the sum of all the numbers less than or equal to 100, or 1000 or something- when I wrote my formula while I was waiting to be picked up at the ymca so it might not look like the one from the internet). So for me I used (n+x)(n/x/2), where n is the limit (for example 1000), and x is the multiple you are using (so 1, or 3, or 5). So if n = 1000 and x = 5, it should find the sum of all multiples of 5 less than or equal to 1000).
Sometimes it adds up correctly and sometimes it doesn't.
For example, if I choose 1 and 2 as the multiples, and 20 as the limit, it prints out 320 (which is correct if you add 1+2+3...+20 and then add to that 2+4+6...+20).
But if I do the multiples of 3 and 5 and 1000 as the limit, it prints out 266,998 (which is wrong according to the internet).
I do not understand why it worked in the first instance but not the second (I have only taken 1 year of high school math, I'll be a sophomore).
Here is the code:
/*
Finds the sum of all inputted multiples below a certain number
For example, it could find the sum of all the multiples of 3 and 5 less than
or equal to 1000
Written By Jay Schauer
*/
//Data Declarations
#include <iostream>
int main()
{
using namespace std;
int a; //Stores the number of multiples being used
cout << "Enter the amount of multiples you would like to use (up to 50
<< endl;
cout << "(for example, enter '2' if you would like to use two multiples,
maybe 3 and 5?)" << endl;
cin >> a;
cout << "Next, you will enter the mutliples you want to use." << endl;
cout << "(for example, if you want to find the sum of the multiples of 3
and\n5 below a given amount, enter 3 as 'multiple 1' and 5 as 'multiple
2')" << endl;
int multiples[50]; //Stores the multiples being used
for (int i = 0; i < a; i++)
{
cout << "Enter 'multiple " << (i + 1) << "'" << endl;
cin >> multiples[i];
}
int limit; //Stores the limit
cout << "Enter the the limit for how high you want to add the multiples
<< endl;
cout << "(for example, you could set the limit to 1000 to find the sum
of the\nmultiples of 3 and 5 (if you entered those) less than and or
equal to 1000)" << endl;
cin >> limit;
int sum(0); //Stores the sum
for (int i = 0; i < a; i++)
{
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
}
cout << "The sum is "<< sum << endl;
system("pause");
return 0;
}
EDIT: I believe the problem might lie in the code not in the formula, because using it on multiples of 3 with 21 as the limit causes it to print out 72, not 84 like it should. I am still unsure of the coding error.
EDIT 2: I changed the for loop to this so it hopefully will function when the limit isn't a multiple of the multiple
for (int i = 0; i < a; i++)
{
int max = limit; /*This is done so I can change max in case it isn't
a multiple of the multiple*/
while (max % multiples[i] != 0) max--;
sum += ((max + multiples[i]) * (max / multiples[i] / 2));
}

Change
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
to
sum += (limit + multiples[i]) * (limit / multiples[i]) / 2;
As it is, for your example of 3 and 21, you're computing (24 * (7 / 2)) = 24 * 3 = 72 (integer division of 7 by 2 gives 3, and the remainder is lost), but you want to be computing (24 * 7) / 2 = 84.

Related

How to use dynamic programming for cutting a rod of length n so that it will be the most profitable

The rod cutting problem is as follows:
Given a rod of length n inches and a table of prices pi for i = 1, 2, ..., n, determine the maximum revenue Rn obtainable by cutting up the rod and selling the pieces. Note that if the price Pn for a rod of length n is large enough, an optimal solution may require no cutting at all.
Consider the following example:
length i 1 2 3 4 5 6 7 8 9 10
price pi 1 5 8 9 10 17 17 20 24 30
Consider the case when n = 4. Cutting a 4-inch rod into two 2-inch pieces produces revenue p2 + p2 = 5 + 5 = 10, which is optimal.Write a program for solving the problem from above such that the time complexity is not higher than Θ(n^2). Your solution has to determine the optimal revenue without the listing of the cuts.
I have developed the following code:
#include <iostream>
#include <stdio.h>
#include <limits.h>
using namespace std;
int max(int a, int b) {return (a > b)? a : b;}
int cutRod(int price[], int n){
int r[n+1];
r[0] = 0; //solution array
for (int i = 1; i <= n; i++){
int q = INT_MIN;
for( int j = 1; j <= i; j++) {
q = max(q, price[j-1] + r[i-j]);
r[i] = q;
}
}
return r[n];
}
int main() {
int price[] = {1, 5, 8, 9, 10, 17, 20, 24, 30};
cout << cutRod(price, 1) << endl;
cout << cutRod(price, 2) << endl;
cout << cutRod(price, 3) << endl;
cout << cutRod(price, 4) << endl;
cout << cutRod(price, 5) << endl;
cout << cutRod(price, 6) << endl;
cout << cutRod(price, 7) << endl;
cout << cutRod(price, 8) << endl;
cout << cutRod(price, 9) << endl;
cout << cutRod(price, 10) << endl;
return 0;
}
I get no errors during compilation, but when I run it the outcome is the following:
1
5
8
10
13
17
20
24
30
32766
which means that for n = 9 and for n = 10, we have that the max revenue is 30 and 32766 respectively. This is wrong as the max revenue for n = 9 is 24 and n = 10 is 30. I have tried re structuring the for loop but I am not able to correct this. My question here is what part of the code is incorrect for the revenues for n => 8 to be incorrect. Any help is much appreciated!!!
You have 9 elements in your array... (Off-by-one)
Also, as a side note, you should use the C++ algorithms instead of your own max function (std::max is in <algorithm>), and in C++ code don't use .h system headers (use their C++ equivalent, so here they would be cstdio, which you don't actually use here, and climits).
As a second side note, you should respect constness (so put a const in front of the int price[] in the argument list, it may show some bugs).
As a third side note, instead of INT_MIN you can just use 0.
As a fourth side note, maybe use std::array? (Though that is purely optional and a matter of preferences! You may need an array, in which case, nevermind.)
As a final side note, since array are 0-indexed in C/C++, you should make your loops start at 0 and not 1 (though once again that is a matter of preferences).
(PS: I just noticed, in the example you provided above you have a 17 twice in the prices, for 6 and 7 units of length.)

Not understanding why code isn't producing desired answer

The assignment I've been given is asking me to find out how many trees can be put in a certain length and how much total space they'd take up including the required space between the trees. Thanks to some help I've been able to get the tree total correct, but the total space taken up is incorrect. What can I do to fix this.
input is: length = 10, TRadius = .5, ReqSpace = 3
desired output is: TreeTot = 2
Total space should be 1.57
Actual output is: TreeTot = 2 Total Space is 6.1
Here is the code I'm using.
#include <iostream>
#include <iomanip>
using namespace std;
const double PI = 3.14;
int main()
{
double length;
double TRadius;
double ReqSpace;
int TreeTot = 0;
cout << "enter length of yard: ";
cin >> length;
cout << "enter radius of a fully grown tree: ";
cin >> TRadius;
cout << "required space between fully grown trees: ";
cin >> ReqSpace;
while (length > TRadius * 2 + ReqSpace) {
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
}
cout << "The total space taken up is ";
cout << setprecision(2) << TreeTot * TRadius * PI + ReqSpace << endl;
cout << "The total amount of trees is ";
cout << TreeTot;
return 0;
}
These two lines:
TreeTot + 1;
length - (TRadius * 2) + ReqSpace;
are valid statements, but they're just expressions. You calculate a value, but don't do anything with it. TreeTot + 1... and then what? You need to assign the calculated value to something. Presumably you're wanting to increase the TreeTot and decrease the length. Just assign the values like so:
TreeTot = TreeTot + 1;
length = length - (TRadius * 2) + ReqSpace;
Or use the shorthand for modifying and assigning the result to the same value:
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
Your answer will probably still be wrong because the if-statement only runs once - you never tell it you want it to do the code within multiple times. If you change the if to a while then the code will loop until length is too small to satisfy the condition.

Dynamic numerical series

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

Getting the second last value of a 4 digit integer

I'm trying a lab exercise which wants user to input a 2 4-digit integer. Then the program will extract all the numbers in the 4-digit integer and use the number to do an arithmetic calculation just like the image link below.
Arithmetic Calculation with 2 4-digit integer
However, the objective for this lab exercise is not to allow me myself, to use a for loop to obtain the result.
For instance, when i want to obtain the last number of the 4 digit integer, I could easily do it by using this.
int firstDigit = firstNo % 10; //i will get 4 if the integer is 1234
int secondDigit = secondNo % 10; //i will get 8 if the integer is 5678
And of course table formatting is nothing to worry about before getting the logic right. Next is a very simple calculation of the numbers using the digit i obtain from the above.
int addfirstNumbers = firstDigit + secondDigit;
int minusfirstNumbers = firstDigit - secondDigit;
int multiplefirstNumbers = firstDigit * secondDigit;
int modfirstNumbers = firstDigit % secondDigit;
double divfirstNumbers = firstDigit / secondDigit;
cout << "add: " << addfirstNumbers << endl
<< "minus " << minusfirstNumbers << endl
<< "multipile " << multiplefirstNumbers << endl
<< "remainder " << modfirstNumbers << endl
<< "division " << divfirstNumbers << endl;
I do understand forloop can make my life easier. But i'm just trying out the long method before trying out the shorter way which is forloop.
But even before i proceed, I'm still unable to extract out the other digit from this 4 digit integer.
Like Mike Vine mentioned in the comments, you can do integer division before taking the modulo.
#include <iostream>
int main(){
int x = 1234;
std::cout << (x/10)%10 << "\n";
}
#Output
3
Edit: This works for all places of a number. To find the nth value from the end, just keep adding 0s to the divisor. For example to find the 2nd from the last, you'd want to divide x by 100 instead.
You could simply do
int secondLastDigit = ((i - (i % 10)) % 100)) / 10;
For i=5678:
i % 10 (5678 % 10) equals 8
i - (i % 10) (5678 - 8) therefore equals 5670.
(i - (i % 10)) % 100 (5670 % 100) equals 70
Finally (i - (i % 10)) % 100) / 10 (70 / 10) = 7
This is pretty simple, just use the modulus operator on the number for 100(num%100), getting the last two digits that way, and then divide that result by ten, and store the digit in an int (so the decimal is properly truncated.)

Encrypt Digit C++

So I am trying to encrypt a four digit integer by adding seven to the digit then dividing the whole digit by ten. In my program I am taking each single digit separately and then I need to divide the whole digit by ten. How can I combine all the separate int into one four digit number?
#include "stdafx.h"
using namespace std;
int main()
{
//Define all variables needed
int a,b,c,d,enc,ext;
//Print dialog and input each single digit for the four number digit
cout << "Enter Your First Digit:" << endl;
cin >> a;
cout << "Enter Your Second Digit:" << endl;
cin >> b;
cout << "Enter Your Third Digit:" << endl;
cin >> c;
cout << "Enter Your Fourth Digit:" << endl;
cin >> d;
//Add seven to each digit
a += 7;
b += 7;
c += 7;
d += 7;
a /= 10;
b /= 10;
c /= 10;
d /= 10;
cout << "Your encrpyted digits:" << c << d << a << b <<endl;
cout << "Enter 1 to exit:" <<endl;
cin >> ext;
if (ext = 1) {
exit(EXIT_SUCCESS);
}
}
As you probably noticed I am dividing each number separately. I need to do them together. Then I am also creating a decrypting which I will get me back to the original number in a separate program.
Based on your comment you are trying to do a variation on the Caesar Cipher, in which case you should be using the modulus operator (%) not the integer division operator (/). Using integer division loses information which will prevent you from decrypting. When your digit is in {0, 1, 2} your division results in a 0. When it is in {3, 4, 5, 6, 7, 8, 9}, the division results in a 1. You can't decrypt {0, 1} back into the original number without some additional information (which you have discarded).
If you want to encrypt on a digit by digit basis using the Caesar Cipher approach, you should be using modulo arithmetic so that each digit has a unique encrypted value which can be retrieved during decryption. If that's really what you are looking for then you should be doing something like the following to encrypt with a 7:
a = (a + 7) % 10;
b = (b + 7) % 10;
c = (c + 7) % 10;
d = (d + 7) % 10;
To decrpyt, you subtract 7, which in mod 10 arithmetic is an addition by 3, so that would be:
a = (a + 3) % 10;
b = (b + 3) % 10;
c = (c + 3) % 10;
d = (d + 3) % 10;
This of course presupposes you've properly validated your input (which isn't the case in your example above).
Combining the individual digits into one four-digit number is simple; just multiple the first digit by 1000, add the second multiplied by 100, and so on.
But this is a one-way algorithm; you will never be able to retrieve the original four-digit number from this.
This is what youd'd probably be looking for :
int e = (a*1000)+(b*100)+(c*10)+d;
e=e/10;
It's not clear from your description whether the addition should be modulo 10 or not; if so
((((((a % 10) * 10) + (b % 10)) * 10) + (c % 10)) * 10) + (d % 10)
if you don't want the modulo 10
(((((a * 10) + b) * 10) + c) * 10) + d
Stepping aside the fact that you almost certainly want mod instead of divide (as #Andand has said), there's more than one way to turn the digits into a number!
A lot of people using interpreted languages these days would probably want to do it symbolically. C++ can do that too, fairly neatly in fact:
// create a string stream that you can write to, just like
// writing to cout, except the results will be stored
// in a string
stringstream ss (stringstream::in | stringstream::out);
// write the digits to the string stream
ss << a << b << c << d;
cout << "The value stored as a string is " << ss.str() << endl;
// you can also read from a string stream like you're reading
// from cin. in this case we are reading the integer value
// that we just symbolically stored as a character string
int value;
ss >> value;
cout << "The value stored as an integer is " << value << endl;
It won't be as efficient as multiplications in this narrow case of a 4 digit number, because of the round trip to a string and back. But good to know the technique. Also it's a style of coding that can be a lot easier to maintain and adapt.
You'll get stringstream if you #include <sstream>.