So I have this program:
#include <iostream>
using namespace std;
bool prime(int input)
{
// cout << "pinput: " << input << endl;
int i = ((input/2) + 1);
// cout << "pi: " << i << endl;
int c;
for (i>0; i--;){
//cout << "pi: " << i << endl;
if (input == 3 || input == 2){
// cout << "true" << endl;
return true;
}
if (input == 1){
// cout << "pi = 1" << endl;
return false;
}
c= input%i;
if (c==0 || i == 1 ){
// cout << "false" << endl;
return false;
}
else if (c!=0 && i<4){
// cout << "true" << endl;
return true;
}
}
return 0;
}
int factor(int input){
// cout << "finput: " << input << endl;
int i = (input/2) + 1;
int c;
int e;
bool d = false;
for (i>0; i--;){
// cout << "fi: " << i << endl;
c = input%i;
if (c==0){
d = prime(i);
if (d==true){
// cout << "found" << endl;
return i;}
}
if (i==1){
// cout << "fi = 1";
return 0;
}
//cout << "not prime" << endl;
}
return 0;
}
int main(){
int woot;
cout << "Please insert quater: " <<endl;
cin >> woot;
int answer;
answer = factor(woot);
if (answer == 0)
cout << "no prime factors" << endl;
else
cout << "answer is: " <<answer << endl;
return 0;
}
It seems to work until I put a really big number in like more specifically the number 600851475143, in which case I always get different answers when I run that number now I'm pretty sure it's just exceeding the size of it's variable type. Now then I was looking and I can't find the right variable type for a number that big, I int and long seem to be for numbers that are for numbers up to 4294967295 if unsigned however that is only 10 digits long, mine is 12. What type of variable should I use? Or will that even fix the problem? The program is to find the largest prime factor of a number (Euler problem 3). Any tips links or advice would be appreciated. And of course an answer extra appreciated! :D
Interesting typo alert!
This is unlikely to be doing what you think it is doing...
for (i>0; i--;){
While it is perfectly legal syntax, and will loop the correct number of times, the value of i inside the loop is (probably) going to be one less than you intended...
% cat 4237157.c++
#include <iostream>
int main()
{
{
std::cout << "Your loop: " << std::endl;
int i = 10;
for (i>0; i--;)
{
std::cout << i << std::endl;
}
}
{
std::cout << "More conventionally: " << std::endl;
for (int i = 10; i > 0; i--)
{
std::cout << i << std::endl;
}
}
return EXIT_SUCCESS;
}
% g++ -o 4237157{,.c++}
% ./4237157
Your loop:
9
8
7
6
5
4
3
2
1
0
More conventionally:
10
9
8
7
6
5
4
3
2
1
The syntax for a for-loop in C-like languages is:
for (variable initialization; conditional; variable increment)
You are evaluating "i>0" instead of doing any initalization. This may as well be blank. Then you are evaluating whether i-- is zero. Since i is post-decremented, your loop starts with i being one less than it was initialized with before the loop, executes until (and including) being equal to zero and then terminates.
A lot of the problems on Project Euler call for arbitrary-precision arithmetic, which isn't covered by the C++ standard library.
Have a look at the C++ Big Integer Library.
If you want arbitarily big numbers, you need an arbitary precision arithmetic library
unsigned long 4294967295
unsigned long long 18446744073709551615
unsigned long long is not standard C++, but most compilers support it as an extension. The maximum should be at least 2^64 - 1, which is more than enough.
If you later want even larger numbers, you can use a arbitrary precision library such as GMP. They have a C++ interface.
Related
This question already has answers here:
Code outside functions
(3 answers)
Closed 3 months ago.
I'm reading from a C++ book (C++ For Dummies) and I'm trying to learn by copying examples from this book and typing them onto an online IDE and I need help learning as to why this code will not run. Thank you. It's very stressful for me and I would love to fully learn this language one day.
#include <iostream>
using namespace std;
int main()
{
int x;
x = 9;
x > 10;
char mychar;
mychar = 'a';
mychar == 'A';
mychar != 'X';
int i = 7;
(i < 10 || i > 100);
if (x > 10)
{
std::cout << "Yuppers, it's greater than 10!" << std::endl;
}
std::cout << "Type any number: ";
std::cin >> i;
if (i > 10)
{
std::cout << "It's greater than 10." << std::endl;
}
else
{
std::cout << "It's not greater than 10." << std::endl;
}
return 0;
}
int i;
std::cout << "Type any number: ";
std::cin >> i;
if (i > 10)
{
std::cout << "It's greater than 10." << std::endl;
}
else if (i == 10)
{
std::cout << "It's equal to 10" << std::endl;
}
else
{
std::cout << "It's less than 10." << std::endl;
}
return 0;
}
I'm not sure why it's not running, but I think it's due to the second half of code, after the first
return 0;
of course
If you remove the highly-verbose comments, you find out that the code in line 126 and afterward is written outside the main function. That's why the program is compiled when everything after line 126 is deleted.
They need to be contained in it before they can be called.
Currently, they are like this:
#include <iostream>
int main(void) {
.
.
}
int i;
std::cout << "Type any number: ";
.
.
This needs to be like this:
#include <iostream>
int main(void) {
.
.
int i;
std::cout << "Type any number: ";
.
.
}
However, int i = 7 is previously declared. So re-declaration will result in a compilation error. As long as i is not a constant, you can reassign it instead.
I am trying to minimize hardcoding numbers into my program and allowing for users to define max and min parameters along with making sure that the input is valid.
#include <iostream>
int main(){
int max, A=0;
do
{
std::cout << "What is the max?\n";
std::cin >> max;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore();
std::cout << "not an integer, try again\n";
continue;
}
if(max < -1000){
std::cout << "That doesnt make much sense, please enter the max again.\n";
}
} while (max <A); \\HERE IS WHERE THE PROBLEM IS.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
If A is 0 or less, the program doesn't ask for user input again. instead the program just exits the loop.
If A is 1 or more, then then the program loops until a valid input is provided.
I would like the max number to be any int number, including negatives. This is working for positive numbers, but not for maximums that are 0 or less.
do
{
//ask for input
//input taken
} while (A>=1);
This will the code you have to use for the scenario described at the last line. One more point you just forget to assign any value to A according to your logic.
Thanks!
If A is 1 or more, then then the program loops until a valid input is provided. - You are saying exactly what the while loop needs to do. Just implement it.
} while (A >= 1); \\If A is greater than or equal to 1 then loop until valid.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
To answer your follow up question:
} while (A >= 1 && max <= 0); \\If A is greater than or equal to 1 then loop until valid.
std::cout << "The max number of steps are " << max <<std::endl;
return 0;
}
I would suggest writing a custom function that takes an acceptable range of min/max values as input parameters, eg:
int promptForInt(const string &prompt, int minAllowed, int maxAllowed)
{
int value;
std::cout << prompt << "\n";
do
{
if (!(std::cin >> value)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "not an integer, try again\n";
continue;
}
if ((value >= minAllowed) && (value <= maxAllowed)){
break;
}
std::cout << "not an allowed integer, enter a value between " << minAllowed << " and " << maxAllowed << ".\n";
}
while (true);
return value;
}
int main(){
int max = promptForInt("What is the max?", -1000, 1000);
std::cout << "The max number of steps are " << max << std::endl;
return 0;
}
I wanted to use only 1 and 0 for the binary. But instead the answer keep giving me the 2nd option with whatever number I typed. I had tried where did I programmed wrongly but unfortunately I still can't find it. So I hoped that I could get some help here.
#include<iostream>
#include<cmath>
using namespace std;
int DualzahlZuDezimal(long long n)
{
int dez = 0;
int i = 0, rem;
while (n != 0)
{
rem = n % 10;
n /= 10;
dez += rem * pow(2, i);
++i;
}
return dez;
}
string a;
int main()
{
long long n;
int dez;
cout << "Test Ein- und Ausgabe : \n";
cout << "----------------------- \n";
cout << "Eingabe einer Dualzahl : ";
cin >> n;
if ((n == '1') && (n == '0'))
{
cout << "Dual : " << n << endl;
cout << "Dezimal : " << DualzahlZuDezimal(n) << endl;
cout << "cin ok ? : ja-ok" << endl;
return 0;
}
else
{
cout << "Dual : 0" << endl;
cout << "Dezimal : 0" << endl;
cout << "cin ok ? : nein-nicht ok" << endl;
return 0;
}
}
If I understand this right, you want the user to enter a binary number, like 10001101001, and you will show the decimal equivalent (1129 in this case).
There are 2 general ways to do that yourself:
You can read the value as a number, as you do, and then apply your conversion
process, except that you check that rem is either 0 (in which case you do
nothing), or 1 (in which case you add the power of 2). If it's another value,
you report the error, and return 0.
You can read the value as a std::string instead. Then you can use
std::find_first_not_of()
to check for contents other than 0 or 1:
if (n.find_first_not_of("01") != string::npos) { /* complain */ }
but then you need to do the conversion based on characters.
But the best approach is not to reinvent the wheel and instead let the standard library handle it for you via stol():
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
int
main()
{
string text;
cout << "Enter a binary number: " << flush;
cin >> text;
size_t endpos = 0;
long decimal_number = stol(text, &endpos, 2); // base 2 == binary
if (endpos != text.size()) {
cerr << "'" << text << "' is not a valid binary number!" << endl;
return 1;
}
else {
cerr << "binary number: " << text << endl;
cerr << "decimal number: " << decimal_number << endl;
return 0;
}
}
Keep in mind that input from the console is text. If you need to check that the text matches a particular format (in this case, consists entirely of 1's and 0's), the simplest approach is to look at that text:
std::string input;
std::cin >> input;
bool input_is_valid = true;
for (int i = 0; input_is_valid && i < input.length(); ++i) {
if (input[i] != '0' && input[i] != '1')
input_is_valid = false;
}
then, if the input is valid, convert the text to a numeric value:
long long n = std::stoll(input);
I am struggling with my program. It should output n Fibonacci numbers, each on a new line. If the Fibonacci number exceeds the range of an unsigned int you should just exit the program. Moreover, you should print on a new line how many Fibonaccis of "n" are displayed.
Here is the code so far:
#include<iostream>
#include<limits>
using namespace std;
int main()
{
unsigned int n;
cout << "Please enter the amount of fibonaccis you would like to compute: " << endl;
cin >> n;
unsigned int next=1;
unsigned int current=0;
unsigned int c = current;
unsigned int temp;
unsigned int counter=1;
//This bool returns true as soon as an overflow occurs
bool overflow;
/*This bool checks, whether the newly computed
number is bigger than the previous number
(which may not be the case if an overflow occurs)*/
bool nextBigger;
/*Somehow, I could only handle the first
inputs by using "bruteforce".
If I tried to combine it with the "main loop",
it got all messy. */
if(n==0)
{
std::cout << "0" << " of " << n << endl;
}
else if(n==1)
{
std::cout << "0" << endl << "1 of " << n << endl;
}
else if(n==2)
{
std::cout << "0" << endl << "1" << endl << "2 of " << n << endl;
}
else
{ /* This for-loop increases (at least it should) a counter
by one for each computation of a valid fibonacci number*/
for(counter=1;counter<n;++counter)
{
overflow = (c > (std::numeric_limits<unsigned int>::max()-temp));
if(!overflow && nextBigger)
{
cout << next << endl;
}
else
{
break; //If overflow or next number < previous number, exit program
}
temp = next; //temp is storage variable for next
c = current; //storage variable for current
next += current; //next is being altered: it becomes the new fibonacci number
current = temp; //current gets value of temp( value of next before being altered)
}
nextBigger = (next > current);
cout << counter << " of " << n << endl; //Output of how many fibonaccis were computed
}
return 0;
}
So here is the thing. I programmed it in CodeBlocks, where it worked perfectly. But then I tried to upload it in Codeboard (as an assignment). In Codeboard it suddenly didn't work at all. Maybe it has to do with the different compilers, but I really have no clue how I could fix this issue. So I am quite puzzled and I'd be very thankful for any hints, ideas, corrections or inspirations.
(I am a beginner, so I hope the code is understandable and readable. I am open for suggested improvements.)
Looking at your code it seems the body of the if statement
if(!overflow && nextBigger)
{
cout << next << endl;
}
is never executed. Maybe print the values for overflow and nextBigger on each loop iteration so you can debug what's happening.
could you please help me with solving simple problem? I am very fresh with C++ and learning from book "Programming: Principles and Practice Using C++ by Bjarne Stroustrup". I have never learnt C++ before so I am not familiar with many useful features. The drill says:
"6. Now change the body of the loop so that it reads just one double
each time around. Define two variables to keep track of which is the
smallest and which is the largest value you have seen so far. Each
time through the loop write out the value entered. If it’s the
smallest so far, write the smallest so far after the number. If it is
the largest so far, write the largest so far after the number"
I do not know how to do this correctly without using vector. Here is my code:
#include "C:/std_lib_facilities.h"
int main()
{
double a, b,differ=0;
char c=' ';
cout << "Enter two values: \n";
while (c != '|' && cin >> a >> b )
{
if (a > b)
{
cout << "The smaller value is: "<< b << " and the larger value is: " << a << "\n \n";
differ = a - b;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else if (a < b)
{
cout << "The smaller value is: " << a << " and the larger value is: " << b << "\n \n";
differ = b - a;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else
{
cout << "These values are equal!\n";
}
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
And here are previous steps, these I have solved with code above:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the
program when a terminating '|' is entered.
Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the
larger value.
Augment the program so that it writes the line the numbers are equal (only) if they are equal.
Change the program so that it uses doubles instead of ints.
Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two
numbers differ by less than 1.0/100.
Could you give me some hint how to do step 6.? I had some ideas but none of them worked..
Here is new code:
#include "C:/std_lib_facilities.h"
int main()
{
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
double a,differ=0;
char c=' ';
cout << "Enter value: \n";
while (c != '|' && cin >> a)
{
if (a > largestSoFar)
{
largestSoFar = a;
cout <<"Largest so far is: "<< largestSoFar << endl;
}
else if (a < smallestSoFar)
{
smallestSoFar = a;
cout <<"Smallest so far is: "<< smallestSoFar << endl;
}
else if(smallestSoFar >= a && a<=largestSoFar)
cout << a << endl;
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
I do not know how to do this correctly without using vector.
You do not need vector for this. The description correctly says that two variables would be sufficient:
// Declare these variables before the loop
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
Modify your loop to read into a, not into both a and b. Check the newly entered value against smallestSoFar and largestSoFar, do the printing, and re-assign smallest and largest as necessary. Note that the first time around you should see both printouts - for largest so far and for smallest so far.
Based on the knowledge that you are suppose to know at the current stage for the this assignment. The code should go something like this:
#include < iostream>
#include < cstdlib>
int main() {
double num_1 = 0;
double num_2 = 0;
double largest = 0;
double smallest = 0;
bool condition1 = true;
while (true) {
std::cin >> num_1;
if (num_1 > largest){
largest = num_1;
}
else if (num_1 < smallest) {
smallest = num_1;
}
std::cout << "The largest so far: " << largest << std::endl;
std::cin >> num_2;
if (condition1) {
smallest = largest;
condition1 = false;
}
if (num_2 < smallest) {
smallest = num_2;
}
else if (num_2 > largest) {
largest = num_2;
}
std::cout << "The smallest so far: " << smallest << std::endl;
}
system("pause");
return 0;
}
double large = 0;
double small = 0;
double input;
int counter = 0;
while (counter < 5) {
cin >> input;
cout <<"Large value: "<< large << '\t' <<"Small value: "<< small\
<< '\t' <<"Input value: "<< input << '\n';
if (input < small) {
cout << "The smallest value is " << input<<\
"\nthe largest value is "<< large<<'\n';
small = input;
}
else if (input > small&& input < large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << large<<'\n';
}
else if (input > small&& input > large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << input << '\n';
large = input;
}
counter += 1;