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
Write a C++ algorithm to test for a prime number. My C++ codes are as follows
#include<iostream>
#include<cmath>
using namespace std;
int x,n;
bool isprime(int);
int main()
{
cout<<"Enter prime no"<<endl;
cin>>x;
for (n=2;n<=floor(sqrt(x));n++)
{
if (x==1)
cout<<"not prime"<<endl;
else if (x%n==0)
cout<<"is not prime"<<endl;
else
cout<<"prime"<<endl;
}
}
But when i run the programn my output does not seem right for example i keep getting "is prime" when the answer is clearly is not prime.The
else if (x%n==0)
cout<<"is not prime"<<endl;
portion of the statement couldnt seem to be excuted properly.Could anyone explain to me what is wrong with my code. Thanks
Your loop outputs "prime" for each non-divisor of x. You should terminate the loop after the first "not prime" hit and only output "prime" if the loop was not terminated.
As suggested by Udo Klein, you should break out of the loop when it is has been detected that the number is not a prime. Also there is no need to check if x is equal to one inside the loop.
#include<iostream>
#include<cmath>
int main()
{
int x;
std::cout << "Enter prime no" << std::endl;
std::cin >> x;
if (x == 1)
{
std::cout << "not prime" << std::endl;
return 1;
}
for (int n = 2; n <= floor(sqrt(x)); n++)
{
if (x % n == 0)
{
std::cout << "is not prime" << std::endl;
return 1;
}
}
std::cout << "prime" << std::endl;
return 0;
}
Related
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 3 years ago.
Improve this question
The problem is to find sum of first and second digit of a number.
If number is smaller than 10 then print number itself.
I wrote this code but i don't know why output is wrong.
#include <iostream>
using namespace std;
int main()
{
int t,a,n,l;
cin>>t;
while(t--)
{
cin>>n;
if(n<10)
{
cout<<n;
}
else
{
a=n%10;
l=n/10;
cout<<a+l<<endl;
}
}
return 0;
}
The reason your solution is wrong because n/10 won't give you the first digit :)
If this is for a question for competitive programming(since you're taking in t test cases), I'll suggest taking input as a string assuming that input is always a valid int.
std::string s;
cin >> s;
if (s.size() == 1) std::cout << s << std::endl;
else std::cout << int(s.front() - '0') + int(s.back()-'0') << std::endl;
extracting of required digits is wrong in your solution.
Please find solution for adding first and last digit of a number at
https://onlinegdb.com/Byro9hCMI or below:
its small and hence pasting it here as well:
#include <iostream>
using namespace std;
int main()
{
int first, last, number;
cin>>number;
first = number % 10;
while((number = number/10)>0)
{
last = number;
}
cout << endl << first+last << endl;
return 0;
}
Two Add first two digit (unit and tens)at https://onlinegdb.com/SJXNThAzI or below:
#include <iostream>
using namespace std;
int main()
{
int first, second, number;
cin>>number;
first = number % 10;
number = number/10;
second = number %10;
cout << endl << first+second << endl;
return 0;
}
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 4 years ago.
Improve this question
I am new to c++ and cant seem to figure out how to simply get an integer from the user and make sure it is between 0-15. Here is my code so far:
When I run the code it only prints Hello world
int main()
{
int greetAndGet();
cout << "Hello";
return 0;
}
int greetAndGet()
{
int i;
cout << "\nPlease give an integer in [1,15]" << endl;
cin >> i;
cout << endl;
}
int greetAndGet(); is a forward declaration of a function, not a call.
Write greetAndGet(); instead.
Note further that a function should be defined/declared before any call to it. So either place the function definition before main, or write
int greetAndGet(); // forward declaration
int main()
{
greetAndGet();
cout << "Hello";
return 0;
}
...
As pointed out in another answer, int greetAndGet() is a forward declaration that you probably intended to be a call; though you do want to forward declare it before main. As for testing the range of the entered value, you could use a loop to check if it is in the range. I think what you want is this:
int greetAndGet();
int main()
{
int num = greetAndGet();
cout << "Hello";
return 0;
}
int greetAndGet()
{
int i;
cout << "\nPlease give an integer in [1,15]" << endl;
do {
cin >> i;
if(i < 1 || i > 15)
{
cout << "Number not in [1,15], please try again" << endl;
}
} while(i < 1 || i > 15);
cout << endl;
return i;
}
I'm not sure what you want to do with the number, but this should get you the entered number.
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 7 years ago.
Improve this question
I need help on something. The textbook I am reading that teaches c++ does not do a good job at teaching students the linear searching algorithm. As a result I have tried recreating the algorithm without using any functions. The problem is, the code I have written seems to have some bugs. Just to note I am using the Microsoft Visual Studios 2013 IDE. As a result, can anyone please tell me what is wrong with my code? Here is the algorithm I have written in English. The Algorithm will not show the variable and array definitions but the source code will.
P.S. This is not a homework assignment. It is just for fun :)
P.S. For some reason the code formatting was very glitchy.
Algorithm:
Ask the user to enter a number
Create a for loop
Inside the for loop traverse through each element in the array and compare
it with the number the user inputted
If the element in the array is EQUAL to the number the user inputted, display a message saying it was found
If the element in the array is NOT EQUAL to the number the user inputted, display a message saying it WASN'T found.
code:
#include <iostream>
using namespace std;
int main()
{
// Create the array
int array[6] = {1,2,3,4,5,6};
int number;
// Ask the user to enter a number
cout << "Enter a number: ";
cin >> number;
// Create a for loop to traverse through each number in the array
//to see if it equals the user inputted number
for (int i = 0; i < 6; i++)
{
if (number == array[i])
{
cout << "Number Found: " << array[i] << endl;
}
else if (number != array[i])
{
cout << "Number Not Found!" << endl;
}
}
return 0;
}
The output if I entered 3 would be the following:
Number Not Found!
Number Not Found!
Number Found: 3
Number Not Found!
Number Not Found!
Number Not Found!
your logic output decision for each iteration. But it seems you've to output your decision only once.
So, for this reason declare a boolean variable globally and set false as a value of this value.
For each iteration check it is found. if found then set the boolean value to TRUE.
for Final output check global boolean value either true or false and print output
Remove the cout from inside the loop. Use a flag, ie if the number is found, set it to true and then write the print statement outside using an if.
int flag=0;
for(int i=0;i<6;i++){
if(number==arr[i])
flag=i+1;
}
if(flag) cout<<"found at position"<<flag;
else cout<<"Not found";
PS: Buy a better textbook
Easier and more fun:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number;
vector<int> nums{1,2,3,4,5,6};
cout << "Find a number: ";
cin >> number;
for_each(cbegin(nums), cend(nums),
[&](const int& x)
{
if(x == number)
cout << "found " << x << endl;
else
cout << "could not find " << endl;
});
}
But a good starting point for linear search would be:
template<typename I, typename T>
I find (I first, I last, const T& val)
{
while (first != last) {
if (*first == val) return first;
++first;
}
return last;
}
This question already has answers here:
C - determine if a number is prime
(12 answers)
Closed 9 years ago.
Can anyone help me out? I am trying to test primality but I cant seem to get this to work. For whatever reason, whenever I run it, it runs fine as long as I start with a number that is not prime. However, after running something that is not prime, the output is "0 1" instead of just 0. It also seems that if I start with a number that is not prime, everything is "0 1" instead of the correct output.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cmath>
int main()
{
int num;
int x = 2;
//cin >> num;
while(cin >> num) //(x<=num-1)
{
for(x<=num-1; x++;)
{
if(num%x==0)
{
cout << "0" << endl ; //1 is prime, 0 is not prime
break;
}
if(x==num)
{
cout << "1" << endl ;
break;
}
}
if(x==num)
{
cout << "1" << endl ;
}
}
return 0;
}
well you have the cout << "1" twice, you probably didn't mean that
for(x<=num-1; x++;)
the semicolons are in wrong places, so instead of stating a condition x<=num-1 under which execution should happen you state the x<=num-1 expression is just evaluated with no effect and then in case of a prime number x is incremented until
if(num%x==0)
is true because in fact num==x at this point. Then you print your '0' and next you print '1' because
if(x==num)
{
cout << "1" << endl ;
}
is true.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to figure out whether a pre or post test loop would be the best method so that the user can continue to input values that will be searched for, until a sentinel value is entered to end the program. Also, what would my parameters look like for the loop? Here is my code, I need to include the loop. Also, I understand that a post test loop is executed at least once. Thanks in advance!
#include<iostream>
using namespace std;
int searchList( int[], int, int); // function prototype
const int SIZE = 8;
int main()
{
int nums[SIZE]={3, 6, -19, 5, 5, 0, -2, 99};
int found;
int num;
// The loop would be here
cout << "Enter a number to search for:" << endl;
cin >> num;
found = searchList(nums, SIZE, num);
if (found == -1)
cout << "The number " << num
<< " was not found in the list" << endl;
else
cout << "The number " << num <<" is in the " << found + 1
<< " position of the list" << endl;
return 0;
}
int searchList( int List[], int numElems, int value)
{
for (int count = 0;count <= numElems; count++)
{
if (List[count] == value)
// each array entry is checked to see if it contains
// the desired value.
return count;
// if the desired value is found, the array subscript
// count is returned to indicate the location in the array
}
return -1; // if the value is not found, -1 is returned
}
Your question is more of a use case dependent.
Post Case: When you need the loop to run AT LEAST once ( 1 or more times)
Pre Case: The loop can run 0 or more times.
I must say, I'm not entirely sure what you want to know. I would honestly recommend a good book on C++. Post test loops are not super popular in C++ (they are of the form "do.. while" where "while" loops / pre test loops are much more common). A little more information is available here: "Play It Again Sam"
EDIT: you need to get data from the user, test it, and then do stuff based on it. Your best bet is something along the lines of
static const int SENTINEL = ??;
int num;
cout << "please input a number" << endl;
cin >> num;
while( num != SENTINEL ) {
// DO STUFF HERE
// Now get the next number
cout << "please input a number" << endl;
cin >> num;
}