This question already has answers here:
Making a square() function without x*x in C++
(7 answers)
Closed 4 years ago.
I'm a beginner in programming and trying to learn C++ by the book Programming principles and practice using C++. In some parts of the book there are little exercises that you can try to do, one of this exercises is about calculating the square of a number, here is what my book says :
Implement square() without using the multiply operator, that is, do the x * x by repetead addition (start a variable result to 0 and add x to it x times).
I've already found a solution for this program but my first tentative was something like this :
#include <iostream>
int main()
{
int a = 0;
std::cout << "Enter an integer value : ";
std::cin >> a;
while (a < a * a)
{
a += a;
std::cout << a << "\n";
}
}
I know this code is wrong but I can't understand the output of the progam, if I enter 5 the program prints 10 20 30 40 50 until 8000, why the for loop doesn't stop when a is greater than its square ? I'm just curious to undersant why
Using multiplication when trying to avoid multiplication seems broken. What about this:
int r = 0;
for (int n = 0; n < a; ++n) {
r += a;
}
why the for loop doesn't stop when a is greater than its square ?
Because it never is. If you compare the graph of y=x^2 against the graph of y=x, you will see that the only time y=x is above, is when 0 < x < 1. That's never the case for integers1. Now, since we're talking about computers with limited storage here, there is a thing called overflow, which will cause a very large number to become a very small number. However, signed integer overflow is undefined behavior in C++. So once your loop gets to the point where overflow would happen, you cannot rely on the results.
1. Note that your loop is not set to stop just when a is greater than its square, but when it is greater than or equal to its square. So, your loop will actually stop if a is 0 or 1.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
So basically this program takes several test cases which consist of a sequence of numbers (of length n). It's supposed to see that, if there exists at least one combination of length x out of the sequence, so that their sum will be odd. It's enough for just one of such combinations to exist. If it's possible, we print "Yes", otherwise "No".
For example, if we input
1 (t=1, one test case)
3 2 (n=3, aka 3 total nrs, x=2, aka consider any 2 of these)
16 11 12 (these are the numbers)
2 even nrs, 1 odd. 11+12 is odd, so the output will be Yes.
My problem is this case particularly
3 3
101 102 103
If I check it on its own, meaning just this one test case, it outputs the correct "No".
If it's with other test cases, meaning it's test 2 or lower, it outputs "Yes".
Can anyone tell me why?
I would really appreciate it.
Here's the code.
#include <iostream>
using namespace std;
int main()
{
int t, n, x, k, c_even{ 0 }, c_odd{ 0 };
string v{"No\n"};
cin >> t;
//t is the number of total cases
for (int i = 1; i <= t; i++)
{
c_even = 0; //counter for even numbers
c_odd = 0; // counter for odd numbers
cin >> n >> x; // n is the total length of the sequence of nrs, x is how many numbers we consider out of the sequence
//this for loop is for introducing the sequence and counting how many nrs are odd and even
for (int j = 1; j <= n; j++)
{
cin >> k;
if (k % 2 == 0)
c_even++;
else c_odd++;
}
//obv if there are no odd nrs, sum won't ever be odd
if (c_odd == 0)
v = "No\n";
/*
for example, say we have 5 odd numbers, 3 even, and we have to consider 5 numbers out of total 8.
the for loop starts with 1. it checks if 1+3>=5, meaning if we have enough even nrs to make odd sum. it's not correct in this case.
then it goes to o=3; it checks if 3+3>=5. correct! so we have enough even nrs to make odd sum. other cases don't have to be considered.
*/
else for (int o = 1; o <= c_odd; o += 2)
{
if (o + c_even >=x)
{
v = "Yes\n";
break;
}
}
cout << v;
}
}
Just had to move string v{"No\n"}; inside the first for.
As cigien said, if string v{"No\n"}; is outside the first loop, in case one iteration sets v as "Yes" and the next one does not satisfy
if (c_odd == 0)
v = "No\n";
in other words, the v remains "Yes", the program will output automatically "Yes", although it is not the correct answer.
By moving that bit of code inside the first for, we assure that each iteration will start with v as "No".
I'm very new to C++ programming, and have written a simple program to calculate the factorial of an integer provided by the user. I am attempting to account for inputs which would cause an error, or do not make sense (e.g. I have accounted for input of a negative number/-1 already). I want to print out an error if the user enters a number whose factorial would be larger than the maximum integer size.
I started with:
if(factorial(n) > INT_MAX)
std::cout << "nope";
continue
I tested this with n = ~25 or 26 but it doesn't prevent the result from overflowing and printing out a large negative number instead.
Second, I tried assigning this to a variable using a function from the 'limits.h' header and then comparing the result of factorial(n) against this. Still no luck (you can see this solution in the code sample below).
I could of course assign the result to a long and test against that but you wouldn't have to go very far until you started to wrap around that value, either. I'd prefer to find a way to simply prevent the value from being printed if this happens.
#include <iostream>
#include <cstdlib>
#include <limits>
int factorial(int n)
{
auto total = 1;
for(auto i = 1; i <= n; i++)
{
total = total * i; //Product of all numbers up to n
}
return total;
}
int main()
{
auto input_toggle = true;
auto n = 0;
auto int_max_size = std::numeric_limits<int>::max();
while(input_toggle = true)
{
/* get user input, check it is an integer */
if (factorial(n) > int_max_size)
{
std::cout << "Error - Sorry, factorial of " << n << " is larger than \nthe maximum integer size supported by this system. " << std::endl;
continue;
}
/* else std::cout << factorial(n) << std::endl; */`
As with my other condition(s), I expect it to simply print out that small error message and then continue asking the user for input to calculate. The code does work, it just continues to print values that have wrapped around if I request the factorial of a value >25 or so. I feel this kind of error-checking will be quite useful.
Thanks!
You are trying to do things backwards.
First, no integer can actually be bigger than INT_MAX, by definition - this is a maximum value integer can be! So your condition factorial(n) > int_max_size is always going to be false.
Moreover, there is a logical flaw in your approach. You calculate the value first and than check if it is less than maximum value allowed. By that time it is too late! You have already calculated the value and went through any overflows you might have encountered. Any check you might be performing should be performed while you are still doing your calculations.
In essence, you need to check if multiplying X by Z will be within allowed range without actually doing the multiplication (unfortunately, C++ is very strict in leaving signed integer overflow undefined behavior, so you can't try and see.).
So how do you check if X * Y will be lesser than Z? One approach would be to divide Z by Y before engaging in calculation. If you end up with the number which is lesser than X, you know that multiplying X by Y will result in overflow.
I believe, you know have enough information to code the solution yourself.
In C++, I should write a program where the app detects which numbers are divisible by 3 from 1 till 10 and then multiply all of them and print the result. That means that I should multiply 3,6,9 and print only the result, which is 162, but I should do it by using a "While" loop, not just multiplying the 3 numbers with each other. How should I write the code of this? I attached my attempt to code the problem below. Thanks
#include <iostream>
using namespace std;
int main() {
int x, r;
int l;
x = 1;
r = 0;
while (x < 10 && x%3==0) {
r = (3 * x) + 3;
cout << r;
}
cin >> l;
}
Firstly your checking the condition x%3 == 0 brings you out of your while - loop right in the first iteration where x is 1. You need to check the condition inside the loop.
Since you wish to store your answer in variable r you must initialize it to 1 since the product of anything with 0 would give you 0.
Another important thing is you need to increment the value of x at each iteration i.e. to check if each number in the range of 1 to 10 is divisible by 3 or not .
int main()
{
int x, r;
int l;
x = 1;
r = 1;
while (x < 10)
{
if(x%3 == 0)
r = r*x ;
x = x + 1; //incrementing the value of x
}
cout<<r;
}
Lastly I have no idea why you have written the last cin>>l statement . Omit it if not required.
Ok so here are a few hints that hopefully help you solving this:
Your approach with two variables (x and r) outside the loop is a good starting point for this.
Like I wrote in the comments you should use *= instead of your formula (I still don't understand how it is related to the problem)
Don't check if x is dividable by 3 inside the while-check because it would lead to an too early breaking of the loop
You can delete your l variable because it has no affect at the moment ;)
Your output should also happen outside the loop, else it is done everytime the loop runs (in your case this would be 10 times)
I hope I can help ;)
EDIT: Forget about No.4. I didn't saw your comment about the non-closing console.
int main()
{
int result = 1; // "result" is better than "r"
for (int x=1; x < 10; ++x)
{
if (x%3 == 0)
result = result * x;
}
cout << result;
}
or the loop in short with some additional knowledge:
for (int x=3; x < 10; x += 3) // i know that 3 is dividable
result *= x;
or, as it is c++, and for learning purposes, you could do:
vector<int> values; // a container holding integers that will get the multiples of 3
for (int x=1; x < 10; ++x) // as usual
if ( ! x%3 ) // same as x%3 == 0
values.push_back(x); // put the newly found number in the container
// now use a function that multiplies all numbers of the container (1 is start value)
result = std::accumulate(values.begin(), values.end(), 1, multiplies<int>());
// so much fun, also get the sum (0 is the start value, no function needed as add is standard)
int sum = std::accumulate(values.begin(), values.end(), 0);
It's important to remember the difference between = and ==. = sets something to a value while == compares something to a value. You're on the right track with incrementing x and using x as a condition to check your range of numbers. When writing code I usually try and write a "pseudocode" in English to organize my steps and get my logic down. It's also wise to consider using variables that tell you what they are as opposed to just random letters. Imagine if you were coding a game and you just had letters as variables; it would be impossible to remember what is what. When you are first learning to code this really helps a lot. So with that in mind:
/*
- While x is less than 10
- check value to see if it's mod 3
- if it's mod 3 add it to a sum
- if not's mod 3 bump a counter
- After my condition is met
- print to screen pause screen
*/
Now if we flesh out that pseudocode a little more we'll get a skeletal structure.
int main()
{
int x=1//value we'll use as a counter
int sum=0//value we'll use as a sum to print out at the end
while(x<10)//condition we'll check against
{
if (x mod 3 is zero)
{
sum=x*1;
increment x
}
else
{
increment x
}
}
//screen output the sum the sum
//system pause or cin.get() use whatever your teacher gave you.
I've given you a lot to work with here you should be able to figure out what you need from this. Computer Science and programming is hard and will require a lot of work. It's important to develop good coding habits and form now as it will help you in the future. Coding is a skill like welding; the more you do it the better you'll get. I often refer to it as the "Blue Collar Science" because it's really a skillset and not just raw knowledge. It's not like studying history or Biology (minus Biology labs) because those require you to learn things and loosely apply them whereas programming requires you to actually build something. It's like welding or plumbing in my opinion.
Additionally when you come to sites like these try and read up how things should be posted and try and seek the "logic" behind the answer and come up with it on your own as opposed to asking for the answer. People will be more inclined to help you if they think you're working for something instead of asking for a handout (not saying you are, just some advice). Additionally take the attitude these guys give you with a grain of salt, Computer Scientists aren't known to be the worlds most personable people. =) Good luck.
I am trying to find the sum of each digit in an integer squared, and for any integer that is input to sqdnumber, it outputs 0 to sqdNumber_result, and I can't figure out why.
Also, this is through edX, but I have been stuck for a week or so on this problem, and I have looked at a lot of different topics, but haven't found anything of use to me.
I used codeblocks to write this, but the system testing it uses codeboard
void squaredSum(int sqdnumber,int &sqdNumber_result) {
for (int i=1; i>1; i++){
if (sqdnumber >= ((10^(i-1))-1)){
int rem = (sqdnumber % (10^i));
int rem1 = (sqdnumber % (10^(i-1)));
int temp = (rem - rem1);
sqdNumber_result = sqdNumber_result + (temp^2);
}
else{
break;
}
}
}
I am new to coding, and just learning to do loops in C++.
This is the first iteration of the loop I have gotten their system to actually give me an output for it(I've written and rewritten it 20 or so times), but it isn't giving me an output that makes sense.
I wouldn't ask but I am at my wit's end.
In C++, ^ is the xor operator, not the nth power. for that, you should use pow.
The for statement does not loop. The condition is false the first iteration
There are two issues:
for (int i=1; i>1; i++){
This loop will not loop at all, since the condition i>1 is never met.
The second issue is the usage of ^ to do a power operation. The ^ in C++ is not a power operator, it is the exclusive-or operator.
So the answer at first glance would be to use the std::pow function to compute powers. However there can be drawbacks using it if the exponent is an integer. The reason is that pow is not guaranteed to work perfectly for integer powers.
See this as to dangers of using pow() for integral exponents
It is advised to just use a simple array of values with the powers of 10 and doing a lookup.
you said you were new to C++ so I tried to get a solution without using the for loop and tried to make it as simple as I could.
Let me know if this was any help.
//Code to calculate the sum of each digit squared//
#include<iostream>
using namespace std;
int main ()
{
int integer1,integer2,sum, square;
cout<<"Please enter two integers"<<endl;
cin>>integer1>>integer2 ;
cout<<"The sum of your integers is"<<" "<<endl;
sum = (integer1+integer2);
cout<<sum<<endl;
cout<<"The square of your sum is"<<" "<<endl;
square = (sum*sum);
cout<<square<<endl;
return 0;
}
I have this piece of code in my school book.
#include<iostream>
using namespace std;
int main() {
int x=10,c=1;
while (c < 5) {
x += x*c;
c *= 2;
c++;
c -= 2;
cout << "X=" << x<<'\n';
}
system("pause");
return 0;
}
As you can see it's an infinite loop, when logically traced, it should show 20,40,80 and so on.
However it always shows 0.
when adding system("pause") after each loop cycle it shows the correct values, but when left as shown above (infinitely looping) it shows zero.
Any ideas of the reason?
c is always 1 no matter what. The loop becomes infinite. Eventually, X becomes 0 due to integer overflow.
c = 1
c *= 2; c = 2
c++; c = 3
c -= 2; c = 1 <-- infinite
Here is my answer for your questions:
Why do you get infinitely looping?
awesomeyi did answer you above, because the condition of the while loop is always true, so it is never ended.
Why does X always equal to 0?
Please pay your attention on X varable, its value will be increased after ending one loop x += x*c. Because you are in the infinitely loop, x's value will be increased forever until greater than the limited value of an integer variable. Then, the value will be set as zero. Please see my output when running your code.
Removing the pause doesn't cause it to always show zero. It just prints output so quickly that zeroes are all you see at the bottom. Add the pause back in and click through about 30-40 iterations and see if it helps you understand what is happening.