while (num > 1)
{
cout << "num is now " << num << endl;
cout << "hello // \n";
num /= 2;
}
I am trying to give the big O estimate for the print statements.
The user gets to input num. I tried a few inputs and am starting to see a pattern.
1 gives 0 print.
2-3 gives 1 print.
4-7 gives 2 prints.
8-15 gives 3 prints.
16-31 gives 4 prints.
let p = the number of prints. I see that the range of numbers giving you a certain amount of prints is 2^p.
So is the big O estimate 2^p ?
You are definitely thinking in the right direction and what is more important - you are approaching the problem in the correct manner. Still your final conclusion is a bit off the target. Try to use 2p for the values you've computed and you will see that the number of prints is not 2p, but rather the inverse of this function.
It's O(log N). The reason is that your halving the range with each iteration. If you're familar with binary search then your loop if doing something similar.
You've correctly observed the 2^p pattern. The inverse of this is log base-2 (rather than log base-10). When people mention log in big-O notation they typically mean the base-2 version.
just use the master theorem.
Link here
b = 2 f(n) = 1 a = 1.
Related
OK, to start off I am a complete beginner in a computer science class. I could ask my teacher, but I don't have time to do so. So, expect some really dumb errors that I can't see and I am using eclipse.
here's my code:
#include <iostream>
using namespace std;
int something()
{
int big = 1000;//largest number is 1000
int small = 1;//smallest number is 1
//so, best guess is to go in the middle
int c;//my guesses
int inequality;//used to write if statements
for (int a = 0; a <= 10; a++)
{
cout << "Think about a number between 1-1000" << endl;//what console tells you
c = (big - small) / 2;//my guess will be the midpoint of the two numbers
while (big > small)//while the highest number is ALWAYS greater than the lowest number
{
cout << "Is your number less than, equal to, or greater than my guess? 1-less,2-equal,3-greater" << c << endl;
cin >> inequality;//you tell me whether my guess is too high, low, or equal
if (inequality == 1)//if you say it is too low...
{
small = c;//the smallest number is now my last guess
c = c - (big - small) / 2;//so, I'll take the midpoint of the CURRENT biggest and smallest number
}
else if (inequality == 2)//if you say it is equal...
{
cout << "Yay, I guessed your number." << endl;//cool.
}
else if (inequality == 3)//if you say it is too high...
{
big = c;//biggest number is now my guess
c = c + (big - small) / 2;//so, I'll take the midpoint of the CURRENT biggest and smallest number
}
}
}
system("pause");
return 0;//returns something in int main function
}
int main()
{
something();//so I can actually do code.
}
So my problem:
If I enter 1 after the console enters the first guess, I get 499, which is fine. After the second guess (where I enter 1), I get 249, which is also fine. However, the third guess after I enter 1 gets a random 681, so could someone help me?
It would be most appreciated if you did not rewrite the entire code for me, otherwise that is really suspicious when I turn it in. I am struggling because I do not have very good computer science background, so to improve, I need ideas mostly. Lastly, any way to make my code look a LITTLE more professional would be appreciated :)
Also, my for loop may be a bit off, I'm not sure.
When you calculate next number you need to change range
So you have first
small guess big
+---------+----------+
if user says too small, then the answer is above the guess, so in the range
big - guess and that is what you need to cut in half so instead of
c = c - (big - small)/2
guess = (big - guess) / 2 + guess
if user says too big then the answer is between guess and small
guess = (guess - small) / 2 + small
Try removing the c+ and c - terms from your midpoint calculations.
Edit: Also, try swapping the small = c and big = c statements in the two conditionals.
Your comments are mostly incorrect and that was my source of confusion.
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.
I am having trouble getting this program to output properly. It simulates a drunken sailor on a board that randomly goes one step to the left or right. At the end of the simulation, the program outputs the percentage of times he fell off the board vs not falling off. My percentage is always zero, and I can't figure out whats wrong with my code.
This function correctly outputs the "experiments" and "fallCount" variable, but always displays "fallCount / experiments" as zero.
This should read "After 2 experiments, sailor fell 1 time, fall percentage was 0.5%"
(if experiments = 2 and fallCount = 1) instead, its 0% every time.
Let me know what I am doing wrong. Thank you!
void outputExperimentStats(int experiments, int fallCount)
{
cout << "After " << experiments << " experiments, sailor fell "
<< fallCount << " time, fall percentage was " << fallCount / experiments << "%\n";
}
That is because you are using integer division. There are no decimals, so things get truncated. E.g.
1 / 2 --> 0 // integer division
This is correct, and expected behavior.
To get the behavior you want, use double or float.
1.0 / 2.0 --> 0.5 // double division
In your example, you can either change the types of your inputs to double or if you want to keep them int, you can convert them during the division
static_cast<double>(fallCount) / static_cast<double>(experiments)
I'm pretty new to Python (just started teaching myself a week ago), so my debugging skills are weak right now. I tried to make a program that would ask a user-submitted number of randomly-generated multiplication questions, with factors between 0 and 12, like a multiplication table test.
import math
import random
#establish a number of questions
questions = int(input("\n How many questions do you want? "))
#introduce score
score = 1
for question in range(questions):
x = random.randrange(0,13)
y = random.randrange(0,13)
#make the numbers strings, so they can be printed with strings
abc = str(x)
cba = str(y)
print("What is " + abc + "*" + cba +"?")
z = int(input("Answer here: "))
print z
a = x*y
#make the answer a string, so it can be printed if you get one wrong
answer = str(a)
if z > a or z < a:
print ("wrong, the answer is " + answer)
print("\n")
#this is the line that's being skipped
score = score - 1/questions
else:
print "Correct!"
print ("\n")
finalscore = score*100
finalestscore = str(finalscore)
print (finalestscore + "%")
The idea was that every time the user gets a question wrong, score (set to 1) goes down by 1/question,so when multiplied by 100 it gives a percentage of questions wrong. However, no matter the number of questions or the number gotten wrong, score remains 1, so finalestscore remains 100. Line 26 used to be:
if math.abs(z)-math.abs(a) != 0:
but 2.7.3 apparently doesn't acknowledge that math has an abs function.
Such a simple accumulator pattern doesn't seem like it would be an issue, even for an older version of Python. Help?
Try score = score - 1.0/questions
The problem is that you're doing integer division, which truncates to the nearest integer, so 1/questions will always give 0.
The problem is that you are using integers for all of your calculations. In particular, when you calculate 1/questions, it truncates (rounds down) to an integer because both values in the calculation are integers.
To avoid this, you could instead use 1.0/questions to make the calculations use floating point numbers instead (and not truncate)
In my c++ class, we got assigned pairs. Normally I can come up with an effective algorithm quite easily, this time I cannot figure out how to do this to save my life.
What I am looking for is someone to explain an algorithm (or just give me tips on what would work) in order to get this done. I'm still at the planning stage and want to get this code done on my own in order to learn. I just need a little help to get there.
We have to create histograms based on a 4 or 5 integer input. It is supposed to look something like this:
Calling histo(5, 4, 6, 2) should produce output that appears like:
*
* *
* * *
* * *
* * * *
* * * *
-------
A B C D
The formatting to this is just killing me. What makes it worse is that we cannot use any type of arrays or "advanced" sorting systems using other libraries.
At first I thought I could arrange the values from highest to lowest order. But then I realized I did not know how to do this without using the sort function and I was not sure how to go on from there.
Kudos for anyone who could help me get started on this assignment. :)
Try something along the lines of this:
Determine the largest number in the histogram
Using a loop like this to construct the histogram:
for(int i = largest; i >= 1; i--)
Inside the body of the loop, do steps 3 to 5 inclusive
If i <= value_of_column_a then print a *, otherwise print a space
Repeat step 3 for each column (or write a loop...)
Print a newline character
Print the horizontal line using -
Print the column labels
Maybe i'm mistaken on your q, but if you know how many items are in each column, it should be pretty easy to print them like your example:
Step 1: Find the Max of the numbers, store in variable, assign to column.
Step 2: Print spaces until you get to column with the max. Print star. Print remaining stars / spaces. Add a \n character.
Step 3: Find next max. Print stars in columns where the max is >= the max, otherwise print a space. Add newline. at end.
Step 4: Repeat step 3 (until stop condition below)
when you've printed the # of stars equal to the largest max, you've printed all of them.
Step 5: add the -------- line, and a \n
Step 6: add row headers and a \n
If I understood the problem correctly I think the problem can be solved like this:
a= <array of the numbers entered>
T=<number of numbers entered> = length(a) //This variable is used to
//determine if we have finished
//and it will change its value
Alph={A,B,C,D,E,F,G,..., Z} //A constant array containing the alphabet
//We will use it to print the bottom row
for (i=1 to T) {print Alph[i]+" "}; //Prints the letters (plus space),
//one for each number entered
for (i=1 to T) {print "--"}; //Prints the two dashes per letter above
//the letters, one for each
while (T!=0) do {
for (i=1 to N) do {
if (a[i]>0) {print "*"; a[i]--;} else {print " "; T--;};
};
if (T!=0) {T=N};
}
What this does is, for each non-zero entered number, it will print a * and then decrease the number entered. When one of the numbers becomes zero it stops putting *s for its column. When all numbers have become zero (notice that this will occur when the value of T comes out of the for as zero. This is what the variable T is for) then it stops.
I think the problem wasn't really about histograms. Notice it also doesn't require sorting or even knowing the