Beginner C++: Strange Behaviour - c++

thanks for taking the time to read this question!
The program is to find the smallest prime number after one billion. at the end of int main() i included a console input cin>>x;with the intention of preventing the command prompt from closing too quickly so i can see the result. however, i realised that i must first enter something before it shows me the result i want.
SO the question is: why is this so even though the console output statement cout<<i;is before the input statement cin>>x;?
#include <iostream>
#include <math.h>
using namespace std;
int is_prime(int x);
int main()
{
for (int i=100000000;;i++){
if(is_prime(i)){
cout<<i;
break;}
int x;
cin>>x;
}
}
int is_prime(int x)
{
double maxvalue = sqrt(static_cast<double>(x));
for ( int i=2;i<=maxvalue;i++){
if (x%i == 0 ) return false; }
return true;
}

It seems like the cin >> x is inside the for loop. So, every iteration of the loop, you will try to read something from the stream. So, you need to enter some numbers before the i becomes prime.
EDIT: Apparently, 1000003 is prime, so you don't have to enter a lot of numbers.

why is this so even though the console output statement cout<<i; is before the input statement cin>>x;?
Because the break changes the order of execution, letting the control skip over cin >> x once the prime is found. You need to move the cin >> x out of the loop.
There are several things that you can do to optimize things quite a bit: rather than trying to divide by every number 1 through sqrt(N), you should divide out only the prime numbers that you have found so far. This would speed things up a lot. You can also drop the call of sqrt by using i*i < x as your exit condition.

Related

How to end program in a do-while (C++)

Here is my code. I am trying to get the entire program to end if it goes into the second if statement inside the do-while loop. But every time I run it, it crashes. I am not sure what I am doing wrong.
#include <iostream>
using namespace std;
int main() {
int myData[10];
for(int i=0;i<10;i++){
myData[i] = 1;
cout<<myData[i];
}
do{
int i;
cout<<endl<<"Input index: ";
cin>> i;
int v;
cout<<endl<<"Input value: ";
cin>>v;
if(i>=0||i<10){
myData[i]=v;
for(int i=0;i<10;i++){
cout<<myData[i]<<" ";
}
}
if (i<0||i>=10){
cout<<"Index out of range. Exit.";
return 0;
}
}while(1);
}
if(i>=0||i<10){
Think about which numbers are either greater than zero or less than ten. I'm sure you realise that is true of all numbers. What you meant to write is
if(i>=0&&i<10){
This explains your crash, you are accessing the myData array with an index that is outside the array bounds.
It's very common for beginners to get && and || confused especially where there is negation involved as well.
Other people have told you the problem:
if(i>=0||i<10){
I'm going to explain why you hit this. You hit it because you didn't use any whitespace.
if (i >= 0 && i < 10) {
Please, please, please, for all that is good in the world, use whitespace liberally. You absolutely will have fewer bugs, because my version is far easier to read. Furthermore if you work with older developers (like me) we can actually read your code far more easily.

No response of a find prime number program

I was stuck in my programming assignment
This assignment is using a bool array to find prime number between 2 to N
The method of it is all prime number "index" will be set on true and other will be set on false,so finally it just print out the true index
Here is my code
#include <iostream>
#include <ctime>
using namespace std;
int main(){
int n,i;
int count = 0;
cout << "Enter the value of n: ";
cin >> n;
bool* prime = new bool[n];
for (i=0;i<=n;i++)
prime[i] = true;
for (i=2;i<=n;i++)
if (prime[i])
for (int j=n;j=i;j--)
if (j%i == 0)
prime[j] = false;
cout << "Prime numbers: ";
for (i=2;i<=n;i++)
if(prime[i])
{cout << i <<", ";
count++;}
cout << count <<" primes found.";
//hold the windows
system("pause");
return 0;
}
The problem of it is after I input the value of N, the program is no response and didn't show any thing out.
Just skimming over your code, I can see that you have used the wrong operator on this line:
for (int j=n;j=i;j--)
Where j=i should be j==i. j=i uses the assignment operator (=) rather than the comparison operator (==), and will always evaluate to true if i is non-zero, thus creating an infinite loop - meaning no output, etc
Side note
You may want to look into bounds-checking for n. What if the user enters a negative number? bool* prime = new bool[n]; would try to produce a negative-sized array, which is not possible (unless the number is converted into an unsigned value, in which case you'd have a huge array of booleans)
I see a bug when looking at the initialization of the array:
bool* prime = new bool[n];
The elements in prime will be from 0 to n-1.
Then, there`s a loop setting the values to true. At some point, i == n:
for (i=0;i<=n;i++)
prime[i] = true;
When i == n, you have written too far in the array. This might overwrite the return address.
Programmers often try to create arrays that are the exact size they need. Unless there`s a lot of storage being needed, I like to create arrays a little bit too big. This reduces the chances of an buffer overflow bug causing an exploit in my code.
bool* prime = new bool[n + 20];
You`d be surprised how many times that practice will save you time.

SIGABRT error for - https://www.codechef.com/problems/PRIME1

I am using sieve of eratosthenes to solve this problem but it is giving me SIGABRT error although my code is working fine on codeblocks....
Please help me modify this code to remove error....
My code is...
#include<vector>
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
unsigned long int t, n, m,i,j;
vector<int> prime;
cin>>t;
while(t--)
{
cin>>m;
cin>>n;
while(!(1<=m&&m<=n&&n<=1000000000&&n-m<=100000))
cin>>m>>n;
prime.resize(n);
for(i=0;i<n;i++)
prime[i]=1;
prime[0]=0;
prime[1]=0;
for(i=2;i<sqrt(n);i++)
{
if(prime[i]==1)
{
for(j=i;i*j<=n;j++)
prime[i*j]=0;
}
}
for(i=m;i<=n;i++)
{
if(prime[i]==1)
cout<<i<<endl;
}
cout<<endl;
prime.resize(0);
}
return 0;
}
Your j loop allows i*j to equal n, but the vector of size n must be indexed from 0 to n-1. The existing code permits referencing an element out of bounds.
The same problem can occur in the last loop, too.
The SIGABRT is issued by library routines.
You have two library routines in your program: std::vector and sqrt.
Either assign sqrt(n) to a const variable or replace the condition with:
(i * i) < n;
You need to verify that:
prime[i*j]
is a valid location. In other words, (i * j) < n.
Some information about primes (that can help you code your program):
Prime numbers are odd except the value 2.
Your test value can start at 3 and add 2 to get to the next value.
You may be able to save some time by looking values in an array of
known values.
Multiplication is usually faster than division. Try rewriting your
test to use multiplication and not division.
Use a data type that can contain the maximum value.

How do I declare a variable in a if-else statement?

I'm still a newbie at this and I really dont understand many things
THE ONLY THING THAT IS MISSING IS x=d/t and I don't know where to put it...
I already tried various methods but still can't figure out where to put it.
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int d, t, s, z;
cout<<"Enter the distance of your destination:"<<endl;
cin >>d;
cout<<"Enter the time you want to get there:"<<endl;
cin >>t;
for (z=1; z<=5; z++)
{
cout<<"Enter your speed:"<<endl;
cin>>s;
if (int x=d/t && x>=s)
{
cout<<"Maintain your speed it is the appopriate speed: "<<s<<"mph"<<endl;
break;
}
else
{
cout<<"Go faster at this rate you won't get to your destination on time"<<endl;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
The Output always shows the if statement even though it should already show the else statement..
I really need help on this..
Just put it outside the if
int x = d / t;
if (x && x >= s)
or maybe you want this
int x = d / t;
if (x >= s)
This is the code:
int main(int argc, char *argv[])
{
int d, t, s, z;
cout<<"Enter the distance of your destination:"<<endl;
cin >>d;
cout<<"Enter the time you want to get there:"<<endl;
cin >>t;
for (z=1; z<=5; z++)
{
cout<<"Enter your speed:"<<endl;
cin>>s;
int x=d/t;
if (x>=s)
{
cout<<"Maintain your speed it is the appopriate speed: "<<s<<"mph"<<endl;
break;
}
else
{
cout<<"Go faster at this rate you won't get to your destination on time"<<endl;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
Write instead:
int x=d/t;
if(x && x>=s)
{
// ...
to get the result exactly for what you have written.
You don't do that.
Use this if you want to do exactly what you've written:
int x = d/t;
if (x && x >= s)
{
...
}
but you probably really just wanted:
if(x >= s)
Try
int x = d/t;
if (x >= s) {
....
As per a book on C++
why declare x at all?
if(d/t>=s)
I guess your problem is that the input data (distance, time) should be double, not int. In C++, division of integers truncates, i.e., 2 / 3 == 0. Has thrown me off a couple of times... Integers are for counting, not for measurements.
And don't worry about writing some expression several times, current compilers are smart enough to notice and compute it once. In any case, write the simplest, clearest code possible. Only if that shows to be too slow (unlikely) does it really pay to go over the code to tighten it up. Your time writing the code, understanding what is really written when it misbehaves, and fixing it is more valuable than a few seconds of computer time.
Never forget Brian Kernighan's "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." Also Donald Knuth's "Premature optimization is the root of all evil".

decimal to binary converter c++?

int inputNumber=0;
int divisionStore=0,modStore=0;
vector<int> mainVector;
cout << "\nEnter a Number to Convert to Binary.\n" << endl;
cin >> inputNumber;
do
{
modStore=inputNumber%2;
inputNumber=inputNumber/2;
mainVector.push_back(modStore);
}while(inputNumber!=1);
for (int i=0;i<mainVector.size();i++)
{
cout<<endl<<mainVector[i]<<endl;
}
Seems like there is a logical error but I cant find whats wrong with it? The program does not print the correct conversion as it seems like the loop ends before it can push the last number.
I think you need to change:
}while(inputNumber!=1)
to:
}while(inputNumber!=0)
Why not use the STL - i.e. bitset
See http://www.cplusplus.com/reference/bitset/bitset/to_string/
Probably do it in a couple lines of code!
Seams to be a very complicated and inefficient way (if I don't misunderstand you). You are probably looking for bit-manipulation operators, not /, % etc. If you really want to stick it in a vector this should do it:
while (inputNumber) {
mainVector.push_back(inputNumber & 1);
inputNumber >>= 1;
}
Note however that this will put the least significant bit at the beginning of the vector, may not be what you want but looks like it is what your code is trying to do as well.
I answered similar question Here, I used recursion function
void decimal_to_binary(int decimal)
{
int remainder = decimal % 2;
if (decimal < 1)
return;
decimal_to_binary(decimal / 2);
cout << remainder;
}
inputNumber%2 is the least significant bit, so your vector will contain the bits in reversed order. Simply loop the vector in reversed order.
while(inputNumber!=1) - You have to loop while inputNumber!=0, otherwise you won't process the last bit.
#include<iostream>
using namespace std;
int main(){
int x,bin;
x=0 ,bin=0;
int ar[10000];
cout<<"Enter Decimal Number "<<endl;
cin>>x;
int n=0;
while(x>0){
bin=x%2;
x=x/2;
ar[n]=bin;
n++;
}
cout<<endl;
n=n-1;
for(n;n>=0;n--){
cout<<ar[n]; }
cout<<endl;
return 0;
}
/* Try this */