fibonacci print out issue in c++ - c++

I was trying to run the fib.exe by using this command "fib 12" so it can directly print out the result in this format:
http://pastebin.com/ytR92i8f
But with my code compiled, for instance, if I use 12 to test my program, it won' t read any number and show the result in this command "fib xx" but it will run the program and let you type the number you want in the next line and then print out the result...
I have attached the link to my main.cpp below as reference.
main.cpp : http://pastebin.com/fhUAkNQR
Because main.c can not be modify so I can only use one function to get it works.
Right now I already have the correct result.
void fibonacci(int max)
{
do
{
std::cin >> max;
}
while(max < 2 && max > 46);
std::cout << " Fibonacci Fibonacci" << std::endl;
std::cout << " N number quotient" << std::endl;
std::cout << "-------------------------------------" << std::endl;
std::cout << " 0 0 N/A" << std::endl;
std::cout << " 1 1 N/A" << std::endl;
int count = max;
int fib1 = 0, fib2 = 1;
for (int i = 2; i <= count; i++)
{
int next = fib1 + fib2;
// Add statements to print here...
std::cout << std::setw(2) << i;
std::cout << std::setw(14) << next;
std::cout << std::setw(21) << std::setprecision(17) << std::showpoint;
std::cout << static_cast<double>(next) / fib2 << std::endl;
std::cout.unsetf(std::ios_base::showpoint);
fib1 = fib2;
fib2 = next;
}
return;
}

Here's and example. Problems like the Fibonacci are better dealt with recursion. I see that with your do while loops you are trying to use some sort of recursion but it's not really working
int fibonacci(int x)
{
if (x == 0)
return 0;
if (x == 1)
return 1;
return fibonacci(x-1)+fib(x-2);
}
This basically does all you've typed in your main, just supply x and enjoy. Recursion is a difficult concept but once you've got the idea it can preform very effectively but it's pretty limited in my opinion.

Related

Why is my function continuing even after I give it wrong input?

I made up a game called password hacker in C++, purpose is to guess the password through given hints, when I input the correct password, it works correct, and moves to the new level as well.
But it does the same even when I input wrong password as well.
#include <iostream>
void Intro(int Level) {
std::cout << "SUP, this PC is locked\n\n" << "well, sure why not give it a try.... it will all be over soon when you type the password incorrectly.\n" << "type your best code here to break security of server number " << Level;
}
bool PlayGame(int Diff) {
Intro(Diff);
int CodeA = 0;
int CodeB = 1;
int CodeC = 2;
int CodeProduct = CodeA * CodeB * CodeC;
int CodeSum = CodeA + CodeB + CodeC;
std::cout << std::endl;
//Instructions
std::cout << "+ 3 number password" << "\n+The numbers adds up to " << CodeSum << "\n+The numbers multiply up to " << CodeProduct << std::endl;
int PlayerGuessA;
int PlayerGuessB;
int PlayerGuessC;
std::cin >> PlayerGuessA >> PlayerGuessB >> PlayerGuessC;
int PlayerSum = PlayerGuessA + PlayerGuessB + PlayerGuessC;
int PlayerProduct = PlayerGuessA * PlayerGuessB * PlayerGuessC;
std::cout << "You entered:\n" << PlayerGuessA << " " << PlayerGuessB << " " << PlayerGuessC;
std::cout << "\n \n Your numbers multiply up to: " << PlayerProduct;
std::cout << "\n Your numbers add up to: " << PlayerSum;
if (PlayerSum != CodeSum && PlayerProduct != CodeProduct) {
std::cout << std::endl << "Like i said earlier, PATHETIC" << std::endl;
return false;
} else {
std::cout << std::endl << "Well, No shit Sherlock " << std::endl;
return true;
}
}
int main() {
int Lev = 1;
while (true) {
bool bLevelComplete = PlayGame(Lev);
std::cin.clear(); //clears any errors
std::cin.ignore(); //discards buffer
++Lev;
}
return 0;
}
Seems to me like you need to put your level up code within your win condition statement, otherwise you're telling the game to keep going regardless of the outcome.
So make Lev global, take the ++Lev out of the main function and put it in the else statement of PlayGame.
OR
Have an if statement wrapped around the ++Lev that takes the return value of PlayGame as it condition. So,
if(bLevelComplete){
++Lev;
}

cargo transportation system we are not sure how to display the last part of our task

Here is our code for the task we are almost finishing just the last part we are stuck at
"Fastest: 3 trips (1 Van, 3 Mini-lorry, $645) "
we are not sure how to display the values in the bracket we only able to display 3 trips.
Is there a way to also display the values in the bracket stated as well?
we use
int min = *min_element(vTrips.begin(), vTrips.end());
cout << "Fastest: " << min << " trips" << endl;
but this only display the 3 trips.
#include <iostream>
#include <vector>
#include <iterator>
#include <fstream>
#include<algorithm>
using namespace std;
class CTS //cargo transport system
{
int i;
int cargo, lorryprice, vanprice, lorrysize, vansize, allOps;
public:
void set_cargo(int);
void set_lorryprice(int);
void set_vanprice(int);
void set_lorrysize(int);
void set_vansize(int);
};
void CTS::set_cargo(int total_cargo) {
cargo = total_cargo;
}
void CTS::set_lorryprice(int lorryP) {
lorryprice = lorryP;
}
void CTS::set_vanprice(int vanP) {
vanprice = vanP;
}
void CTS::set_lorrysize(int lorryS) {
lorrysize = lorryS;
}
void CTS::set_vansize(int vanS)
{
vansize = vanS;
}
int main()
{
int cargo, lorryprice, vanprice, lorrysize, vansize, options, i, no_lorry, no_van, cost, trips;
ifstream infile;
infile.open("size.txt");
if (infile.is_open()) {
infile >> cargo;
infile >> lorryprice;
infile >> vanprice;
infile >> lorrysize;
infile >> vansize;
}
CTS run;
run.set_cargo(cargo);
run.set_lorryprice(lorryprice);
run.set_vanprice(vanprice);
run.set_lorrysize(lorrysize);
run.set_vansize(vansize);
infile.close();
options = (cargo / lorrysize) + 1;
no_lorry = (cargo / lorrysize);
no_van = (cargo / vansize) + 3;
if (cargo % lorrysize == 0) {
no_van = -3;
}
if (cargo % lorrysize != 0) {
no_van = ((cargo % lorrysize) / 10) - 3;
}
/*it = numbervan.begin();
for (auto ir = numbervan.rbegin(); ir != numbervan.rend(); ++ir) {
cout << *ir << endl;
}*/
vector<int> vCost, vVan, vTrips, vLorry;
vector <int>::iterator it;
for (i = 1; i < options + 1; i++)
{
int numberlorry = no_lorry;
cout << "Option " << i << ":" << endl;
cout << "Number of Mini-Lorries : " << no_lorry-- << endl;
if (no_van >= -3) {
no_van += 3;
}
cout << "Number of Vans : " << no_van << endl;
int numbervan = no_van;
if (numberlorry > numbervan) {
trips = numberlorry;
}
else {
trips = numbervan;
}
cout << "Trips Needed : " << trips << endl;
cost = (numberlorry * lorryprice) + (no_van * vanprice);
cout << "Total Cost : $" << cost << endl;
vCost.push_back(cost);
vLorry.push_back(numberlorry);
vVan.push_back(numbervan);
vTrips.push_back(trips);
}
int counter = vCost.size() - 1;
//std::vector<int>::reverse_iterator ir = vCost.rbegin();
for (i = 1; i < 4; i++) {
//cout << "Lowest #" << i << ": "<<cost<<endl;
cout << "Lowest #" << i << ": $" << vCost[counter] << "(" << vVan[counter] << " Vans, " << vLorry[counter] << " Mini-Lorry, " << vTrips[counter] << " Trips)" << endl;
counter--;
}
int min = *min_element(vTrips.begin(), vTrips.end()); // this line of code we figured out how to
cout << "Fastest: " << min << " trips" << endl; //display the number of trips using algorithm
return 0;
}
Your design is awkward; you create an instance of CTS run; and never use it.
Assuming that you do your calculations right, you need to know at what index you found min. If you store the iterator returned by min_element(), you can get an index by subtracting vTrips.begin() from it. Then the corresponding elements in your vCost, vLorry and vVan vectors will contain the data you want.
However, it would be easier if you define a struct containing your pre-calculated values, and push that into some vector. In that case, all related data is kept together.

Integer overflow and std::stoi

if x > INT_MAX or if x > INT_MIN the function will return 0... or that's what i'm trying to do :)
in my test case i pass in a value that is INT_MAX + 1... 2147483648 ... to introduce integer overflow to see how the program handles it.
i step through... my IDE debugger says that the value immediately goes to -2147483648 upon overflow and for some reason the program executes beyond both of these statements:
if (x > INT_MAX)
if (x < INT_MIN)
and keeps crashes at int revInt = std::stoi(strNum);
saying out of range
Must be something simple, but it's got me stumped. Why isn't the program returning before it ever gets to that std::stoi() given x > INT_MAX? Any help appreciated. Thanks! Full listing of function and test bed below: (sorry having trouble with the code insertion formatting..)
#include <iostream>
#include <algorithm>
#include <string> //using namespace std;
class Solution {
public: int reverse(int x)
{
// check special cases for int and set flags:
// is x > max int, need to return 0 now
if(x > INT_MAX)
return 0;
// is x < min int, need to return 0 now
if(x < INT_MIN)
return 0;
// is x < 0, need negative sign handled at end
// does x end with 0, need to not start new int with 0 if it's ploy numeric and the functions used handle that for us
// do conversion, reversal, output:
// convert int to string
std::string strNum = std::to_string(x);
// reverse string
std::reverse(strNum.begin(), strNum.end());
// convert reversed string to int
int revInt = std::stoi(strNum);
// multiply by -1 if x was negative
if (x < 0)
revInt = revInt * -1;
// output reversed integer
return revInt;
}
};
Main:
#include <iostream>
int main(int argc, const char * argv[]) {
// test cases
// instance Solution and call it's method
Solution sol;
int answer = sol.reverse(0); // 0
std::cout << "in " << 0 << ", out " << answer << "\n";
answer = sol.reverse(-1); // -1
std::cout << "in " << -1 << ", out " << answer << "\n";
answer = sol.reverse(10); // 1
std::cout << "in " << 10 << ", out " << answer << "\n";
answer = sol.reverse(12); // 21
std::cout << "in " << 12 << ", out " << answer << "\n";
answer = sol.reverse(100); // 1
std::cout << "in " << 100 << ", out " << answer << "\n";
answer = sol.reverse(123); // 321
std::cout << "in " << 123 << ", out " << answer << "\n";
answer = sol.reverse(-123); // -321
std::cout << "in " << -123 << ", out " << answer << "\n";
answer = sol.reverse(1024); // 4201
std::cout << "in " << 1024 << ", out " << answer << "\n";
answer = sol.reverse(-1024); // -4201
std::cout << "in " << -1024 << ", out " << answer << "\n";
answer = sol.reverse(2147483648); // 0
std::cout << "in " << 2147483648 << ", out " << answer << "\n";
answer = sol.reverse(-2147483648); // 0
std::cout << "in " << -2147483648 << ", out " << answer << "\n";
return 0;
}
Any test like (x > INT_MAX) with x being of type int will never evaluate to true, since the value of x cannot exceed INT_MAX.
Anyway, even if 2147483647 would be a valid range, its reverse 7463847412 is not.
So I think its better to let stoi "try" to convert the values and "catch" any out_of_range-exception`. The following code illustrates this approach:
int convert() {
const char* num = "12345678890123424542";
try {
int x = std::stoi(num);
return x;
} catch (std::out_of_range &e) {
cout << "invalid." << endl;
return 0;
}
}

Which are the best methods for speeding up the algorithm based on vector search?

I am trying to solve the Euler question 419
So far, I think I managed to build an algorithm to find the answer. Or at least it gives the correct result for first 40 step. But I need to compute 1,000,000,000,000th step. Solving first 40 step (with my algorithm) takes about 3-4 seconds. And bigger the iteration number increases, computation time increases as well. I don't think my computer can solve 1,000,000,000,000 iteration in a year.
What I do is simply using temporary vectors for both sequential number counting(form_1 and form_2) and keeping the calculated the result for each iteration(testVec). Here is my code below:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <cmath>
std::vector<int> form_1;
std::vector<int> form_2;
std::vector<int> testVec;
void showVec(std::vector<int>& vec)
{
//
for (unsigned long int i = 0; i < vec.size(); i++)
{
//
std::cout << vec[i] << std::endl;
}
}
void resFin(int start, int stop, std::vector<int>& vec)
{
//
for (unsigned long int i = 0; i < vec.size(); i++)
{
//
if (i == 0)
{
//
form_1.push_back(vec[0]);
//std::cout << "form_1 pushed " << vec[0] << std::endl;
}
else
{
//
if (i != vec.size() - 1)
{
//
if (vec[i] == vec[i - 1])
{
//
form_1.push_back(vec[i]);
//std::cout << "form_1 pushed " << vec[i] << std::endl;
}
else
{
//
form_2.push_back(form_1.size());
form_2.push_back(vec[i - 1]);
form_1.clear();
form_1.push_back(vec[i]);
}
}
else
{
//
if (vec[i] == vec[i - 1])
{
//
form_1.push_back(vec[i]);
//std::cout << "form_1 pushed " << vec[i] << std::endl;
form_2.push_back(form_1.size());
//std::cout << "form_2 pushed " << form_1.size() << std::endl;
form_2.push_back(vec[i - 1]);
//std::cout << "form_2 pushed " << vec[i - 1] << std::endl;
form_1.clear();
}
else
{
//
form_2.push_back(form_1.size());
//std::cout << "form_2 pushed " << form_1.size() << std::endl;
form_2.push_back(vec[i - 1]);
//std::cout << "form_2 pushed " << vec[i - 1] << std::endl;
form_2.push_back(1);
//std::cout << "form_2 pushed " << 1 << std::endl;
form_2.push_back(vec[i]);
//std::cout << "form_2 pushed " << vec[i] << std::endl;
form_1.clear();
}
}
}
}
vec.clear();
for (unsigned long int k = 0; k < form_2.size(); k++)
{
//
vec.push_back(form_2[k]);
//std::cout << "vec pushed " << form_2[k] << std::endl;
}
//showVec(vec);
if (start + 1 != stop)
{
//
form_1.clear();
form_2.clear();
std::cout << "recursed to " << start + 1 << std::endl;
resFin(start + 1, stop, vec);
}
}
void stepFind(int stop, std::vector<int>& vec)
{
//
resFin(1, stop, vec);
}
void trimmVec(std::vector<int>& vec)
{
//
int a = 0;
int b = 0;
int c = 0;
for (unsigned long int i = 0; i < vec.size(); i ++)
{
//
switch (vec[i])
{
case 1:
a++;
a = a % 1073741824;
break;
case 2:
b++;
b = b % 1073741824;
break;
case 3:
c++;
c = c % 1073741824;
break;
default:
break;
}
}
std::cout << "a is " << a << "; b is " << b << "; c is " << c << std::endl;
}
int main()
{
//
testVec.push_back(1);
testVec.push_back(1);
stepFind(39, testVec);
//showVec(testVec);
trimmVec(testVec);
getchar();
return 0;
}
I think no one ought to wait more than a few hours to solve euler problems right? So I am doing something wrong here. So, are there such methods existed to minimize computing time, especially in vectors inside searching(I think this consumes the time most)?

My switch statement won´t let me use a particular variable as an expression

What I want is for it to let the user guess the number as many times as it takes to guess it, then tell him the number of times it took him to guess it, that´s why im making the condition for the for loop g!=r, however, I have no idea if C++ allows this.
Also, the errors I get when trying to compile this are
expression must have a constant value
expression did not evaluate to a constant" and "case expression not constant
Here´s the code:
int main()
{
int r = rand() % 101;
int g = 0;
int t = 10;
std::cout << "Guess a number, human (From 1 to 100)." << std::endl;
std::cin >> g;
for (int t = 0; g != r; t++)
{
switch (g) {
case (g == r):
std::cout << "You won, now get lost!" << std::endl;
break;
case (g < r):
std::cout << "Too low, piece of turd." << std::endl;
break;
case (g > r):
std::cout << "Too high, dubai." << std::endl;
break;
default :
std::cout << "How could you possibly have gotten it wrong, you stupid ape." << std::endl;
}
}
std::cout << "Finally!, it took you " << t << " freaking times!" << std::endl;
return 0;
}
The switch case checks must be constant expressions that are compared for equality against the original value.
In your case, you can rewrite that switch using if commands.
Use the code below, and it will compile.
if (g == r)
{
std::cout << "You won, now get lost!" << std::endl;
}
else if (g < r)
{
std::cout << "Too low, piece of turd." << std::endl;
}
else if (g > r)
{
std::cout << "Too high, dubai." << std::endl;
}
else
{
// will not get here, as previous if already cover all cases
std::cout << "How could you possibly have gotten it wrong, you stupid ape." << std::endl;
}
C++ switch
http://en.cppreference.com/w/cpp/language/switch
C++ if
http://en.cppreference.com/w/cpp/language/if
If you're required to use a switch, you might try using a while loop with a flag and some checks before the switch:
bool flag = true;
int t = 0;
int x = 0;
while( flag )
{
t++;
std::cout << "Guess a number, human (From 1 to 100)." << std::endl;
std::cin >> g;
if( g == r )
{
x = 1;
flag = false;
}
else if( g < r )
x = 2;
else
x = 3;
switch (x) {
case (1):
std::cout << "You won, now get lost!" << std::endl;
break;
case (2):
std::cout << "Too low, piece of turd." << std::endl;
break;
case (3):
std::cout << "Too high, dubai." << std::endl;
break;
default :
std::cout << "How could you possibly have gotten it wrong, you stupid ape." << std::endl;
}
}
I changed it to an if statement, and now after the first guess, the user isn´t able to guess again.
ok, the new code here:
int main()
{
int r = rand() % 101;
int g = 0;
int t = 0;
std::cout << "Guess a number, human (From 1 to 100)." << std::endl;
std::cin >> g;
for (int t = 0; g = r; t++)
{
if (g < r)
{
std::cout << "Too low." << std::endl;
std::cin >> g;
}
else if (g > r)
std::cout << "Too high." << std::endl;
std::cin >> g;
}
std::cout << "Finally!, it took you " << t << " freaking times!" << std::endl;
return 0;
}