The following program is to find the sum of even-valued fibonacci terms not more than four million.
The last 'cout' statement in this program doesn't get executed at all. Why is it? Help please.
#include <iostream>
using namespace std;
int main()
{
int a, b, c, sum, sum1, sum2;
a = 1;
b = 2;
sum2 = 0;
cout << b << endl;
c = a + b;
sum1 = c;
while (c <= 4000000)
{
a = b;
b = c;
if ((a + b) <= 4000000)
{
c = a + b;
if (c%2 == 0)
{
sum2 = sum2 + c;
cout << c << endl;
}
}
}
cout << "The sum of even fibonacci numbers not greater than 4 million is: " << (sum1 + sum2); //Not being executed
return 0;
}
I can't execute the program, but I think that your program never ends, which is why you never get to that statement. Your outer while loop will keep on going unitl c <= 4000000. However, you only increment c if and only if (a + b) <= 4000000, so c never goes beyond 4 million.
To fix this, you could try the below:
#include <iostream>
using namespace std;
int main()
{
int a, b, c, sum, sum1, sum2;
a = 1;
b = 2;
sum2 = 0;
cout << b << endl;
c = a + b;
sum1 = c;
while (c <= 4000000)
{
a = b;
b = c;
c = a + b; //Update c regardless.
if (c <= 4000000)
{
if (c%2 == 0)
{
sum2 = sum2 + c;
cout << c << endl;
}
}
}
cout << "The sum of even fibonacci numbers not greater than 4 million is: " << (sum1 + sum2); //Not being executed
return 0;
}
while ( c <= 4000000 )
{
// ...
if ( ( a + b ) <= 4000000 )
{
c = a + b; // i.e. <= 4000000
// ...
}
}
How do you expect that loop to terminate?
Related
I have been asked by my teacher to solve this problem: "You get 3 different numbers as input, of different length, you have to determine the sum of the digits of all 3 numbers and also the product"
I solved it like this:
#include <bits/stdc++.h>
using namespace std;
int main () {
int a, b, c, S, P;
cin >> a >> b >> c;
S = 0;
P = 1;
while (a != 0) {
int c1 = a % 10;
S += c1;
P *= c1;
a /= 10;
}
while (b != 0) {
int c1 = b % 10;
S += c1;
P *= c1;
b /= 10;
}
while (c != 0) {
int c1 = c % 10;
S += c1;
P *= c1;
c /= 10;
}
cout << S << ' ' << P << endl;
}
My question is, is there a way to solve this more efficient?
You should bother not about the fastest way that does not make sense for such a simple program but about the correctness of the code and avoiding its duplication.
Your program is just incorrect.
For starters the user can interrupt the input. In this case at least one of the variables a, b, c will have indeterminate value. As a result the program will have undefined behavior.
Secondly, as you are using the signed int type when the user can enter negative numbers. In this case you will get an incorrect result because for example sum of digits can occur to be negative.
Thirdly, the user can enter 0 as a value of a number. In this case this number will be skipped in a while loop like this
while (a != 0) {
In this case you again will get an incorrect result because the product of digits can be not equal to zero though it must be equal to zero in this case.
The same while loops are duplicated. That is the program has a redundant code.
The program can be written the following way as it is shown in the demonstrative program below.
#include <iostream>
int main()
{
long long int a = 0, b = 0, c = 0;
std::cin >> a >>b >> c;
long long int sum = 0;
long long int product = 1;
for ( int num : { a, b, c } )
{
const long long int Base = 10;
do
{
long long int digit = num % Base;
if ( digit < 0 ) digit = -digit;
sum += digit;
if ( product ) product *= digit;
} while ( num /= Base );
}
std::cout << "sum = " << sum << '\n';
std::cout << "product = " << product << '\n';
return 0;
}
Move the repeated code to a separate function.
#include <iostream>
using namespace std;
void calc(int num, int &sum, int &product) {
do {
int c1 = num % 10;
sum += c1;
product *= c1;
num /= 10;
}
while (num != 0);
}
int main () {
int a, b, c, S = 0, P = 1;
if (cin >> a >> b >> c) {
calc(a, S, P);
calc(b, S, P);
calc(c, S, P);
cout << S << ' ' << P << endl;
}
return 0;
}
I'm having problems with some homework and I can't find the answer.
I have to do a simple program that solves a math problem, but it does not comp
This is the code:
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
int a, b, FirstA;
int result = 0;
FirstA = a;
// The sum of the cubes between a and b: (a^3 + (a + 1)^3 + .. + (b + 1)^3 + b^3)
while (cin >> a >> b) {
for (a; a <= b; a++) {
result = result + pow(a,3);
}
cout << "suma dels cubs entre " << FirstA << " i " << b << ": " << result << endl;
}
}
The error it gives is this:
program.cc: In function ‘int main()’:
program.cc:23:15: error: statement has no effect [-Werror=unused-value]
for (a; a <= b; a++) {
All warnings being treated as errors.
What should I do?
You have an unused value in for (a; a <= b; a++) because the a; makes no sense.
Use a for-loop without initialization: for (; a <= b; a++).
Your function is not resembling the formula in the comment above it and the for loop is not defined properly: for (a; a <= b; a++).
A possible solution is to replace:
for (a; a <= b; a++) {
//---^
result = result + pow(a,3);
}
with:
cin >> a >> b;
int n = 10; // number of iterations
int i = 0;
int j = n;
do{
++i;
--j;
result += pow(a + i, 3) + pow(b + j, 3);
}while(i <= n);
I'm trying to print all common multiples of two integers smaller than a certain limit(100 in my case). However, when I call my function, it does nothing. This is my code:
void com_mul(int a, int b)
{
int original = b;
for(int i = 1; a <= 100; i++)
{
a *= i;
b = original;
for(int j = 1; b <= a; j++)
{
b *= j;
if(a == b)
cout << b << ", ";
}
}
}
You can solve this problem much simpler, using a single loop.
In a for loop iterate over potential divisors d from 1 to 100. If d divides both a and b, print d.
You can tell if a number divides another number by applying the % operator, and checking the result for zero:
if (a%d == 0 && b%d == 0) {
cout << d << endl;
}
Tested with a = 4, b = 2, max = 100 on my machine. And it outputs 4.
This is because of the line for (int j = 1; b <= a; j++). j can only go upto 'a'
I think this would do.
#include <iostream>
#include <string>
int main()
{
int a, b, max;
std::cin >> a >> b >> max;
for (int i = a; i <= max; i++)
{
if (i%a == 0 && i%b == 0)
std::cout << i << std::endl;
}
return 0;
}
I wanted to practice math in c++ and I tried making a program that answered this question from math class
0 < r < 1, find the number of rational r values for which the
numerator and the denominator add to make 1000 where r is in simplest
form
After an hour or two debugging, I finally got something that makes it through all the numbers. In class, the answer was 200. I got 216. Run for yourself
#include <math.h>
#include <iostream>
bool rprime_test(int a, int b) {
int tmp = 2;
std::cout << a << "/" << b;
tmp1:
for (tmp; (tmp < a) && (a % tmp != 0); tmp++) {
}
if ((b % tmp == 0 && a % tmp == 0) || b % a == 0) {
std::cout << " == irreduced\n";
return false;
} else if (!tmp < a) {
std::cout << " == reduced\n";
return true;
} else {
//std::cout << tmp << ","<< a << std::endl;
goto tmp1;
}
}
int main() {
int r = 0, a = 1;
int b = 1000 - a;
while (a < b) {
if (rprime_test(a, b)) {
r++;
}
std::cout << "total = " << r << std::endl;
a++;
b = 1000 - a;
//std::cout << "assigned " << a << "/" << b << std::endl;
}
std::cout << "final result = " << r << std::endl;
return 0;
}
please I don't know what I did wrong for this. Also, is there any better way to optimize this?
Your main issue is with your rprime_test function. Without digging too much into your existing function, try using the gcd. Two numbers a and b are an irreducible fraction when they are "coprime," which is when their "greatest common denominator" (gcd) is 1. The way you compute the gcd of two values is with the Euclidean Algorithm:
int gcd (int a, int b) {
return b % a == 0 ? a : gcd (b % a, a);
}
And your check becomes
if (gcd (a, b) == 1) {
a++;
/* etc */
}
Following works:
#include <iostream>
int gcd(unsigned int a, unsigned int b)
{
if (b < a) {
return gcd(b, a);
}
int r = a % b;
while (r != 0) {
a = b;
b = r;
r = a % b;
}
return b;
}
int main()
{
int count = 0;
for (int i = 1; i != 500; ++i) {
if (gcd(1000 - i, i) == 1) {
++count;
}
}
std::cout << count << std::endl;
}
Live example
I need to write a function head that returns the number of representations of a number as a sum of 3 positive squares.
For example, the only representation of 3 as a sum of 3 squares is 3 = 1+1+1, so the function should return 1 if number = 3. If n is 27, the function should return 2 since 27 has two representations 27 = 25 + 1 +1 or 9+9+9.
This is what I have tried:
#include <iostream>
#include <cmath>
using namespace std;
int numRep(int num);
int main()
{
int count = numRep(27);
cout << count;
return 0;
}
int numRep(int num)
{
int count = 0, sum = 0;
int a =1, b=1, c=1;
while(a*a <= num -2)
{
b = 1;
while(b*b <= num -2)
{
c =1;
while(c*c <= num -2)
{
sum = a*a + b*b + c*c;
if (sum == num) count++;
c++;
}
b++;
}
a++;
}
return count/3;
}
But I am not getting correct output. Need some guidance... If there is a better method, do suggest..
Here is a good starting point:
#include <cmath>
#include <iostream>
int count_sum_of_squares(int n)
{
int count=0;
// We only need to test numbers up to and including the square root of n.
// Also, we want to impose an ordering on [a, b, c] to consider
// combinations and NOT permutations.
for (int a=1; a<=int(sqrt(n)); ++a)
for (int b=1; b<=a; ++b)
for (int c=1; c<=b; ++c)
if (a*a+b*b+c*c==n) // If the squares of {a, b, c} add up to n
++count; // then this is a case that should be counted
return count;
}
int main()
{
std::cout << 3 << ': ' << count_sum_of_squares(3) << '\n';
std::cout << 14 << ': ' << count_sum_of_squares(14) << '\n';
std::cout << 27 << ': ' << count_sum_of_squares(27) << '\n';
std::cout << 866 << ': ' << count_sum_of_squares(866) << '\n';
}
Instead of searching from 1 to num - 2, you should only search from the current index loop above. That way, you don't repeat any terms.
#include <iostream>
#include <cmath>
using namespace std;
int numRep(int num);
int main()
{
int count = numRep(27);
cout << count << endl;
return 0;
}
int numRep(int num)
{
int count = 0, sum = 0;
int a =1, b=1, c=1;
while(a*a <= num -2)
{
b = a;
while(b*b <= num -2)
{
c =b;
while(c*c <= num -2)
{
sum = a*a + b*b + c*c;
if (sum == num) {
count++;
}
c++;
}
b++;
}
a++;
}
return count;
}
You're getting all the permutations, and you want all the combinations.
Example: numRep(14) will give you 6, when I think you want it to only have 1.
a = 1, b = 2, c = 3
a = 1, b = 3, c = 2
a = 2, b = 1, c = 3
a = 2, b = 3, c = 1
a = 3, b = 1, c = 2
a = 3, b = 2, c = 1
You'll need to keep track of your answers, preferably sorted with a-c going from lowest to highest, and don't increment your count if it already exists.
This works for me:
int numRep(int num){
int count = 0;
for(int a = 1; a * a <= num ; ++a)
for(int b = a; b * b <= num ; ++b)
for(int c = b; c * c <= num ; ++c)
if (a*a + b*b + c*c == num)
count++;
return count;
}
Only start with b from a, and with c from b so you won't count twice the same solution.
The complexity of this is O(N*sqrt(N)) I think.
Just start second loop from a. And you don't need a third loop at all. c = sqrt(num - a*a - b*b). If this calculated c is an integer, then it counts.