I need to write a code to calculate the following sum:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int m,n;
cin>>n>>m;
float sum = 0.0, prod = 1.0;
int i = 2;
while(i <= n)
{
int j = 3;
while(j <= m)
{
prod = prod * (float)(i*i/j);
j++;
}
sum+=prod;
i++;
}
cout<<sum<<endl;
return 0;
}
However, getting a wrong answer and I guess it's because (float)(i*i/j) this part. It's rounding the fraction. How to fix this little problem?
Recast j:
prod = prod * (i * i / (float)j);
This will promote the product to a float.
Some rules of conversion may be useful, generally: https://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions
Related
I am writing some code that prints out a sum series using a loop and a function.
I intend the equation to look like this
m(i) = (1/2) + (2/3) + ... (i / i + 1)
The problem is that my code always gives me incorrect answers and not printing what it's supposed to. For example, when I input 1 into 1 the answer should be 0.5
This is my code:
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(1);
return 0;
}
void sumSeries(int x){
double sum = 0;
for(int i = 0; i < x; i++){
sum = (x/x + 1);
sum += sum;
}
cout<<sum;
}
Indeed, you overwrite your sum but also take care of your integer division.
You may change it as sum += i/(double)(i + 1);
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(5);
return 0;
}
void sumSeries(int x){
if (x<0)
{
return;
}
double sum = 0;
for(int i = 0; i < x; i++){
sum += i/(double)(i + 1);
}
cout<<sum;
}
I see two problems in your code.
First: (x/x+1) != (x/(x+1)), in this case C++ obeys the normal point before line calculation rules.
Second: You are overwriting your sum in each iteration, instead of that you should direct add to sum: sum+=x/(x+1)
And a third issue, as noted by Simon Kraemer, is that you are using integer division, to get the correct results you must cast at least one of the operands to a floating point number.
What you want is:
void sumSeries(int x){
double sum = 0;
for(int i = 1; i <= x; i++){ // include i in the list
sum += static_cast<double>(i)/(i + 1); // force the operation as double
}
cout<<sum;
}
your mathematical expression has something not normal. Do you mean M(i)= sum(1-i){i/i+1}? , or 1/2 and 1/3 are constants?
in your case as gerum answered it is a small Operator Precedence problem to learn how the C++ compiler prioritize the operators follow here.
your function also should have a guard against zero denominator (undefined values).
Also you should observe that you take int/int division which will ignore the remaining value. then you should consider that by converting the numerator or the denominator to double before the division here .
then your code should be:
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(1);
return 0;
}
void sumSeries(int x){
double sum = 0;
for(int i = 0; i < x; i++){
if ((x+1)!=0){
sum += (double)x/(x + 1);
}
// the else will apply only if x==-1
else {
cout<<"the denominator is zero"<<endl;
throw;
}
}
cout<<sum;
}
So..
Here is the code:
#include <iostream>
#include <limits>
#include <math.h>
using namespace std;
int main()
{
unsigned long long i,y,n,x=45;
unsigned long long factorial = 1;
for(n = 0; n <= 5; n++)
{
y = (pow(-1,n)*pow(x,2*n)) / factorial;
cout << "COS IS " << y << endl;
}
for(int i = 1; i <=n; i++)
{
factorial *= 2*i;
}
}
I get an overflow but I really don't know why. I use unsigned long long just to make sure that I on't get but.. I still get it. Even limited to small numbers. I tried to implement this:
https://en.wikibooks.org/wiki/Trigonometry/Power_Series_for_Cosine_and_Sine
But I really can't do it because of the overflow. Do you have any ideea on what can I do ? I am newbie in programming so, take it easy on me :D
There are many issues.
you use integer types when you should use floating point types
you use unsigned types for signed calculations
you don't use radians but degrees (45° ≈ 0.78539 radians)
you don't calculate the factorial in the loop, it is always 1, you only calculate it at the end of the loop but then it's too late, and your calculation of the factorial is wrong anyway.
the algorithm is wrong, it just doesn't do what Maclaurin's therorem says, you need to sum up the terms, but you just print the terms.
You probably want this:
#include <iostream>
#include <cmath>
using namespace std;
long factorial(int n)
{
long result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
int main()
{
double x = 0.785398163397448309616; //PI/4 expectd result COS(PI/4) = 0.7071067
double mycosinus = 0;
for (int n = 0; n <= 5; n++)
{
mycosinus += (pow(-1, n) * pow(x, 2 * n)) / factorial(2*n);
cout << "COS IS " << mycosinus << endl;
}
}
This is your wrong algorithm for calculating the factorial of 5:
int main()
{
int n = 5;
int factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= 2 * i;
}
cout << "factorial 5 = " << factorial << endl;
}
The calculated value is 3840 instead of 120. I let you find out what's wrong yourself.
For performing this sort of maths you need to use a floating point like float or double not integral types like long, int or long long, given that sin and cos can both return negative numbers you shouldn't be using unsigned either.
#include <iostream>
#include <math.h>
int main()
{
double result = sqrt(4732);
int intResult = (int)result;
result = result - (double)intResult;
double first = result;
while(1)
{
result = 1/result;
intResult = (int)result;
result = result - intResult;
std::cout<<intResult<<std::endl;
double absDiff = result > first ? (result-first):(first-result);
if(absDiff < 0.000001)
break;
}
return 0;
}
I am trying to calculate continued fraction of square root of 4732. Here is the wiki description for the continued fraction.
https://en.wikipedia.org/wiki/Continued_fraction
The correct answer is [68;1,3,1,3,45,1,1,2,11,15,5,34,5,15,11,2,1,1,45,3,1,3,1,136].
My code goes in an infinite loop. Here is the output from the first few iterations.
[68;1,3,1,3,45,1,1,2,11,15,5,126,..
Note that the output starts diverging from here.
I have checked this code for other numbers like 9999, 13, 12, etc. and it is giving the correct answer.
Can anybody point me to the problem in the code?
Thanks in advance.
Update: I used float128 as well. But it does not solve the issue. It looks like I may have to use some another algorithm to avoid losing precision.
Thanks to interjay for pointing me to how to solve the problem. Here is the code that gave the correct results for me. The key here is not to use floating point arithmetic as it would propagate error even if you use 128 bits of precision.
#include <iostream>
#include <math.h>
int main()
{
int num = 4732;
double result = sqrt(num);
int intResult = (int)result;
int a = intResult;
int b = 1;
int first_a = a;
int first_b = b;
do
{
double temp = (double)b/ (result - (double)a);
int I = (int)temp;
int new_a = (I*((num - (a*a))/b)) - a;
int new_b = (num - (a*a))/b;
a = new_a;
b = new_b;
std::cout<<I<<std::endl;
}
while((first_a != a) || (first_b != b));
return 0;
}
I have the following code which calculates, for the number of terms of your choosing, the square root of 6 * [ 1 + 1/(2^2) + 1/(3^2)....1/(n^2)]. In this case, I'm going with 100 terms. If I am given what the output should be, is there a way to, using my existing code, determine how many terms were used to get to that output?
#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[]) {
long double square = 0;
for (int i = 1; i <= 100; i++) {
long double squareExp = i*i;
square += 1/(squareExp);
}
long double sixTimes = 6 * square;
long double squareRoot = sqrt(sixTimes);
printf("%.8Lf", squareRoot);
return 0;
}
I tried making it so that I take the desired output (3.141592), squaring it and dividing by 6 to negative the square root and (*6), and tried running this code:
double temp = 3.141592 * 3.141592;
double tempB = temp / 6;
printf("%f\n", tempB);
int reachedZero = 0;
int valueOfN = 0;
long double square = 0;
while (square > 0) {
int i = 1;
square -= 1/i;
i++;
if (square <= 1) {
reachedZero = 1;
valueOfN = i;
break;
}
}
printf("%i", valueOfN);
return 0;
}
I can't figure out what to do. I want to take the number (after getting rid of the square root and multiplying by 6), and subtract numbers starting with 1, then 1/4, then 1/9, then 1/16...1/(n^2) until the number becomes negative. Once that happens, I set a flag and I know how many terms I needed to reach that #. I then set that specific counter to a variable, which I can print out.
#EugeneSh. This was a working solution for me. Basically matched the pi output I was looking for with my loop, checking it each time. Could have changed the for loop to a while loop but it works fine this way.
int main(int argc, const char * argv[]) {
long double square;
for (long i = 1; i>=1; i++) {
square += 1.0/(i*i);
long double sixTimes = sqrt(6 * square);
if (sixTimes >= 3.141592) {
printf("%li", i);
break;
}
}
return 0;
}
i wrote a code that calculates and outputs a difference between the sum of the squares of the first ten natural numbers and the square of the sum.
The problem is with function squareOfSum(). The function should return 3025 but it always returns 3024. Even if i try to put 100 into brackets i get 25502499 (25502500 is correct). No matter what number i put into brackets i always get the same problem.
What am I doing wrong?
Here's a screenshot of my output.
#include <iostream>
#include <cmath>
using namespace std;
int sumOfSquares(int limit);
int squareOfSum(int limit);
int main()
{
cout << sumOfSquares(10) << endl;
cout << squareOfSum(10) << endl;
cout << squareOfSum(10) - sumOfSquares(10) << endl;
}
int sumOfSquares(int limit)
{
int sum = 0;
for(int i = 1; i<=limit; i++)
{
sum +=pow(i,2);
}
return sum;
}
int squareOfSum(int limit)
{
int sum = 0, square = 0;
for(int i = 1; i<=limit; i++)
{
sum +=i;
}
square = pow(sum,2);
return square;
}
Note that pow is a function that works with floating point numbers. Optimizations might lead to rounding errors or truncation during implicit coversion to int. Replace pow(i, 2) with i*i and you'll get pure integer arithmetic and thus exact results.
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main()
{
int higher_limit = 100;
int SquaresOfSum = 0;
int SumOfSquares = 0,count=0;
for(int i=1;i<=higher_limit;i++){
count += i;
SumOfSquares += pow(i,2);
}
SquaresOfSum = pow(count,2);
cout<<SquaresOfSum-SumOfSquares;
}
Using Javascript
const sumSquareDifference = (n) => {
const numbers = [...Array(n + 1).keys()];
const sumOfSquares = numbers.reduce((accumulator, number) => accumulator + (number ** 2));
const squareOfSum = numbers.reduce((accumulator, number) => accumulator + number) ** 2;
return squareOfSum - sumOfSquares;
}
console.log(sumSquareDifference(10));