C++ - Recursive counter [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to create a counter. It counts each operation such as multiplication, addition, subtraction, division. Every time I try to cout the counter, it stays as zero.
Can anyone shed any light on what I am doing wrong?
A bulk of my code is missing so I can protect it from other classmates, however I have listed how many operations is in that section where the code would be.
long karatsuba(int num1, int num2, int &counter)
{
if (num1 < 10 || num2 < 10)
{
counter++ // 1 operation
return num1 * num2;
}
/* calculates the size of the number */
... 4 operations
/* split the digit sequences about the middle */
... 4 operations
/* 3 calls made to numbers approximately half the size */
int z0 = karatsuba(..., ..., counter);
int z1 = karatsuba(..., ..., counter);
int z2 = karatsuba(..., ..., counter);
return ... // 9 operations
}
-------------------------------------------------------------
int main()
{
int counter = 0;
cout << karatsuba(123, 456, counter) << " " << counter << endl;
cout << endl;
system("Pause");
return 0;
}

The problem is this line:
cout << karatsuba(123, 456, counter) << " " << counter << endl;
Try instead
cout << karatsuba(123, 456, counter);
cout << " " << counter << endl;
the problem is cout, count is still 0 when it prints.

Related

Trouble finding sum of odd integers cubed [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Tried several times yet still didnt manage to find my mistake: here is my program. i need to find the odd numbers from 1 and integer x and find the sum of them cubed.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x;
int i = 1;
int result;
cout <<" Enter the value for n" << endl;
cin >> x;
while (i >x)
if (i%2 == 0) {}
else {
result += pow(i,3);
i++;
}
cout << "The sum of odd integers cubes from " << i << " to " << x << "= " << result << endl;
return 0;
}
Minimally, you should change the compare in while
from
while (i > n)
to
while (i <= n)
There a many numbers where i will be greater than the number entered, n.
You didn't add in your curly brackets for the while loop.
while (i > x)
if (i%2 == 0) {}
needs to be:
while (i > x){
if (i % 2 == 0) {}
}
Plus what are you doing inside of that if statement? You should decrement x, to find if each number is odd.
Plus, your program ends early because i is 1 and if the user enters a number above 1, your while loop won't even run. You're telling the while loop to run ONLY when i is larger than x. Try changing it to less than:
from:
while (i > x){
to:
while (i < x){
Plus you're not doing anything with x. You want to decrement x, not add i. Although, I would recommend using a do-while loop. ( a dowhile loop does one iteration first before incrementation)
do{
if (x % 2 == 0) { // if the remainder of x/2 is 0, do this
x--;
cout << "Equal: " << x << endl;
}
if(x % 2 != 0) { //if the remainder of x/2 is not 0, do this.
temp = pow(x,3);
//you don't want to take the power of the added sum,
//you were taking the power 3 of x which was being added to.
//you want to add the sums of each power. So here we have temp, a
//temporary variable to store your addends.
result = result + temp;
cout << "Not equal, temp:" << temp <<endl;
cout << "Result: "<< result << endl;
x--; //you didn't have a decrement, you need to bring x eventually down to i if you want the loop to end, or even look through all of the numbers
}
}
while (i < x);
//You have to have this semi colon here for the compiler to know its a do-while.
cout << "The sum of odd integers cubes from " << i << " to " << userVar
<< " = " << result << endl;
return 0;
}
note: if-else statements are for flow control, its like true and false, one or the other, so that your data will flow somewhere. I used two if statements because I want to have complete control over the flow.
note2: It's ok to use:
using namespace std;
at first, but eventually you want to start learning what library each command is using. When you get into more complex programming, you start using commands from different libraries than the standard one.

how to find series of a numbers those have 5 or more factors in a given range in c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
#include
using namespace std;
int main()
{
int n, i;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factors of " << n << " are: " << endl;
for(i = 1; i <= n; ++i)
{
if(n % i == 0)
cout << i << endl;
}
return 0;
}
I understand the below problem of finding factors of numbers. But i want to do a c++ program which only show the numbers which have 5 or more factors. suppose i give a range of numbers 15 to 20.then it will print only those numbers those have 5 or more factors. such as example if i give a range 15 to 20 then it will print out only 16,18,20.because these 3 integers have 5 or more factors in 15 to 20 range. i couldnt understand how to do that code so i am asking.
As I understood you are searching the tech finding number prime factors of an natural number. Firstly the code you published is for getting all the divisor's of given positive number. But Finding its prime factors a little bit different but the idea same as you used (modular arithmetic)
this is a very simple version of achieving your task (but needs optimization)
#include <iostream>
//This function does not handle the repeating factors count
int numberOfPrimeFactors(int number) {
int count = 0;
for ( int i = 2; i <= number; ++i ) {
while ( number % i == 0 ) {
number /= i;
count++;
}
}
return count;
}
int main() {
int Rbegin = 1;
int Rend = 100;
for(int i = Rbegin; i<Rend; ++i) {
if(numberOfPrimeFactors(i) >= 5)
std::cout << i << " has 5 or more prime factor"<< std::endl;
}
}

Variable not being set and returning a unusual number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a function that is being used to calculate the damage caused towards an object
string Weapon::attack(int Damage, int ExtraDamage, string Type)
{
srand(time(NULL));
int totalDamage = 0;
int percentileDie = rand() % 100 + 1;
if (percentileDie <= ChanceToHit) {
for (int i = 0; i <= Damage; i++)
{
int sixSidedDie = rand() % 6 + 1;
totalDamage = totalDamage + sixSidedDie;
}
totalDamage = totalDamage + ExtraDamage;
}
else {
totalDamage = 0;
}
Result = totalDamage;
if (Type == "Crossbow") {
return "Twang! ";
}
else if (Type == "Dagger" || Type == "Sword") {
return "Swing! ";
}
}
However, when I go and call the variable Result in my program, I get the number -858993460. I changed Result = totalDamage to Result = 6 to see if it would return 6 but it once again returned -858993460.
Can anyone help me out?
If I do this:
Weapon t;
t.attack(2, 4, "Sword");
cout << t.attack(2, 4, "Sword") << t.Result << endl;
I get the correct number, but if I do this:
Weapon t;
cout << t.attack(2, 4, "Sword") << t.Result << endl;
I get the number -858993460 again!
Also, Result is declared in a class:
class Weapon {
public:
string Name;
int Damage, ExtraDamage, Result;
float ChanceToHit;
string attack(int,int,string);
};
The order of evaluation of cout << X << Y is not ordered for X and Y.
So this code:
Weapon t;
cout << t.attack(2, 4, "Sword") << t.Result << endl;
will evaluate either t.attack() or t.Result first - based on your post, it would seem that t.Result is evaluated first.
The solution is to force the compiler to do things in the correct order, e.g.
Weapon t;
std::string str = t.attack(2, 4, "Sword");
cout << str << t.Result << endl;
If you look into what exactly is going on here, then you will realize that operator "<<" is being used to add data to output stream.
The "<<" operator is defined to add data on stream and return a reference of modified stream for further use, this is the reason we can use multiple "<<" in single "cout" So the order of putting values on stream is reverse of the order in which you read it.
So it is like
cout<<firstOperand<<secondOperand<<thirdOperand;
is evaluated as
cout(<<firstOperand(<<secondOperand(<<thirdOperand)));
Which in turn means that "thirdOperand" is added to output stream first then updated stream is returned. Now "secondOperand" is pushed to the same returned stream similarly and then "firstOperand" is pushed to the output stream. Now all "<<" operators are done. Now cout puts the stream content on the output file.
So, in your case, because t.Result is getting added to output stream before its calculation in class function, the value that you get is random value of Result initialized during object construction.

Not entering while loop? [closed]

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 7 years ago.
Improve this question
[EDIT] - Nevermind, this is a really dumb question
I'm currently trying to create a program that will basically tell me when insertion sort takes a longer time than merge sort for given a, b and n (in this case, successive powers of 2). This is what I have so far:
int comparisonSort()
{
//prompt user for values of a and b
int a = 0;
int b = 0;
cout << "Enter the value for a" << endl;
cin >> a;
cout << "Enter a value for b" << endl;
cin >> b;
double insertionSortTime = 0;
double mergeSortTime = 0;
double n = 2;
cout << outside while loop" << endl; //check
while (insertionSortTime < mergeSortTime)
{
cout << "inside while loop" << endl; //check
//compute the insertion and merge sort execution times
insertionSortTime = a*n*n;
mergeSortTime = b*n*log2(n);
cout << "is = " << insertionSortTime << " ms = " << mergeSortTime << endl;
n = pow(n, 2); // n^2
}
cout << "value of n that insertion sort beat merge sort is: " << n << endl;
return 0;
}
when I run this, I get:
Enter the value for a
8
Enter a value for b
64
outside while loop
value of n that insertion sort beat merge sort is: 2
I have no idea why the while loop isn't getting executed... Sorry if this seems like a really simple question, but I'm new to C++ and any help would be greatly appreciated, thank you!!
The conditional in
while (insertionSortTime < mergeSortTime)
is false in the first iteration when both insertionSortTime and mergeSortTime are set to zero. That explains why the loop never got executed.
Perhaps you meant to use:
while (insertionSortTime <= mergeSortTime)
Its because you have insertionSortTime = 0 and mergeSortTime = 0 and the condition for your loop is insertionSortTime < mergeSortTime.
Of course 0 is not < 0 so it never enters the loop.
Change it to <=.

Array returing greatest value with index [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am trying to get the greatest value from the array and its index number also by using a function maxin but my logic somehow isn't working?
#include <iostream>
#include <conio.h>
#include <proceass.h>
void maxin(double[], int);
void main()
{
const int k = 10;
int l = 0;
double num[k];
for (int j = 0; j < k; j++)
{
cout << "Enter the number " << j + 1 << " = ";
cin >> num[j];
if (cin.fail())
{
cout << "Wrong data entered " << "\nTry again";
getch();
exit(0);
}
}
maxin(num, l);
cout << "The Greatest number is = " << num;
cout << "\nIt is " << l << "th number";
getch();
}
void maxin(double k[], int p)
{
int l, s;
l = 10;
s = 0;
double m;
for (int n = 0; n < l; n++)
{
if (k[s] > k[n++])
{
m = k[n];
}
else
{
m = k[n++];
s = ++;
}
}
p = s;
k[s] = m;
}
Your maxin function is invoking Undefined Behavior on your program for causing access to areas beyond the bounds of the array k. This happens because not only is n incremented in the for loop statement, but again in the if statement which is evaluated on each iteration as well. This also happens in the else statement, which is another case of the problem.
When n is 1 less than l, n++ will be >= l, and subsequently dereferencing that address, k[n++], will cause Undefined Behavior. After that, anything can happen to your program, including valid or invalid side effects.
When finding the maximum/minimum value in an array, a variable is usually set to an arbitrary value in the array (typically the first index), and then iteration is performed to check if any other value in the array is smaller/larger than that variable. When that condition passes, the variable is set to the new value in the array.
Furthermore, since you said you needed to set the variable to the index at which the largest value was found, it is necessary that you pass p by reference.
The STL approach:
vector< double > v = {1,2,3,4,5};
auto maxElemIter = std::max_element(begin(v), end(v));
cout << "Max is: " << *maxElemIter;
cout << ", at index: " << distance(begin(v), maxElemIter) << endl;
(I know, this is a cruel suggestion, given code as stated in question above...)