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.
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 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;
}
This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 7 years ago.
Guys why this code become an infinite loop? I'm learning C++ so if you can explain the solution, for me would be very important!
// Odd_or_Even.cpp : This program determinate if a number is Odd or Even
//
#include "stdafx.h"
#include "std_lib_facilities.h";
int main()
{
int num = 0;
bool repeat = true;
while (repeat == true)
{
cout << "Please enter an integer to determinate if it's odd or even: ";
cin >> num;
cout << "\nReading data...";
if (!cin) {
cout << "Failed\n";
cout << "There is some problem with the number, sorry!\n";
cout << "\n";
cin.clear();
}
else
{
cout << "God job, now stop lose time.";
repeat = false;
}
}
keep_window_open();
return 0;
}
Thanks!
EDIT: ok i writed the if for block the loop, but if you try to write a letter, instead of a number, it still go in a loop!!
It's an infinite loop because you never update repeat. Your while loop will continue to run until repeat is set to equal 0 or false.
P.S. since repeat is a Boolean value, while(repeat) is the same as while(repeat==true)
Your code sets repeat to true and then your while loop runs while
while(repeat == true)
To get it out of an infinite loop you need to do this somewhere inside the while loop:
repeat = false;
On what condition would you like to break out of the loop?
I am fairly new to C++ still, as well as programming and the terms used. I'm learning off of "Programming: Principles and Practice Using C++" (as was gifted to me) and I ran into a problem on a Drill at the end of chapter four. The drill is split into twelve exercises, where the first five are as follows:
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.
I've dealt with those exercises, but now I don't quite get what to do in the next exercise:
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 don't get it. What should I do with the loop? What's exercise 6 actually about?
My code I have made up so far from step five is as follows:
#include <iostream>
#include <vector>
#include <algorithm>
//Name
int main()
{
char terminate = ' ';
double one = 0.0;
double two = 0.0;
int one_i = one;
int two_i = two;
while (terminate != '|')
{
std::cout << "Input two numbers, follow each one by enter: " << std::endl;
std::cin >> one;
std::cin >> two;
if (one == two)
{
std::cout << "The two numbers are equal to each other." << std::endl;
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
if (terminate == '|')
{
break;
}
}
std::cout << "Here is the larger value: ";
if (one > two)
{
std::cout << one << std::endl;
}
else
{
if (two > one)
{
std::cout << two << std::endl;
}
}
std::cout << "Here is the smaller value: ";
if (one < two)
{
std::cout << one << std::endl;
if (one_i == two_i || two_i == one_i)
{
std::wcout << "The numbers are almost equal." << std::endl;
}
}
else
{
if (two < one)
{
std::cout << two << std::endl;
if (one_i == two_i || two_i == one_i)
{
std::wcout << "The numbers are almost equal." << std::endl;
}
}
}
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
}
}
I attempted to figure out the problem if this code helps any of you see as to what degree I'm confused on.
#include <iostream>
#include <vector>
#include <algorithm>
//Name
int main()
{
char terminate = ' ';
std::vector<double>num_size;
while (terminate != '|')
{
std::cout << "Type in a number: " << std::endl;
for (double num; std::cin >> num;)
{
num_size.push_back(num);
std::sort(num_size.begin(), num_size.end());
}
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
}
}
Well, you didn't finish step 5. 999 and 1000 are almost equal (difference < 1%).
Ignoring that, your second fragment is a good start at producing the behavior wanted in step 6 but ignores the prescribed method. Yes, a sorted vector has a .front() and a .back() which are the respective minimum and maximum, but step 6 specifically told you to use two variables instead of a whole vector.
So double max = std::numeric_limits<double>::max(); double min = -max; and from there on you should be able to figure it out.
You want something like:
double my_max = numeric_limits<double>::max();
double my_min = -1 * numeric_limits<double>::max();
while (...) {
...
my_min = min(my_min, one);
my_min = min(my_min, two);
my_max = max(my_max, one);
my_max = max(my_max, two);
I'm new to programming and to c++ so I know this is probably a silly question but I would really appreciate the help. just as the tittle says, I'm trying to make a subtraction while type loop that reaches a desired value, in this case: 0
The code uses two random numbers from the user input. The first number is the minuend, the second is the subtrahend
However, the problem that I'm having is that if subtraction surpasses desired value, the loop will not display it and the user will see displayed a number higher value than 0. I want to fix so it displays the negative number closest to 0 and then stop. Here's the code:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
cout <<" enter a: ";
cin >> a;
cout << "enter b: ";
cin >> b;
while ( a > 0 )
{
cout << a << '\n';
a= a-b;
}
return 0;
}
What am I doing wrong, how can I fix it? Thanks
You're printing a before decreasing it. Try switching the statements inside your loop like so:
while ( a > 0 )
{
a = a - b;
cout << a << '\n';
}
You could just add
cout << a << '\n';
again after your loop - you know you have the right value then. Or you could possibly avoid duplicating that line by switching to using a do ... while loop.
Hi i just switched this code:
while ( a > 0 )
{
cout << a << '\n';
a= a-b;
}
to this and it worked as you explained:
while ( a > 0 )
{
a= a-b;
cout << a << '\n';
}
What I am trying to do is search for a perfect number.
A perfect number is a number that is the sum of all its divisors, such as 6 = 1+2+3.
Basically what I do here is ask for 2 numbers and find a perfect number between those two numbers. I have a function that tests for divisibility and 2 nested loops.
My issue is that I don't get any result. I've revised it & can't seem to find anything wrong. The compiler doesn't shoot out any errors.
What can be wrong?
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main()
{
int startval;
int endval;
int outer_loop;
int inner_loop;
int perfect_number = 0;
cout << "Enter Starting Number: ";
cin >> startval;
cout << "Enter Ending Number: ";
cin >> endval;
for(outer_loop = startval; outer_loop <= endval; outer_loop++)
{
for(inner_loop = 1; inner_loop <= outer_loop; inner_loop++)
{
if (isAFactor(outer_loop, inner_loop) == true)
{
inner_loop += perfect_number;
}
}
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
else
{
cout << "There is no perfect number." << endl;
}
}
system("PAUSE");
return 0;
}
bool isAFactor(int outer, int inner)
{
if (outer % inner == 0)
{
return true;
}
else
{
return false;
}
inner_loop += perfect_number; should be perfect_number += inner_loop;.
There are other issues -- you need to reset perfect_number to zero in each outer loop, and you should presumably print the message "There is no perfect number." if none of the numbers in range is perfect, rather than printing it once for every number in range that is not perfect.
I'd advise that you rename perfect_number to sum_of_factors, outer_loop to candidate_perfect_number and inner_loop to candidate_factor, or similar.
after the if statement:
cout << perfect_number;
cout << outer_loop;
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
and see what values they have
Updated:
What is the value of your endval? is 0?, and thats why the loop ends so early
Oh, so many issues.
The variable perfect_number never changes. Did your compiler flag
this?
The outer loop will be one more than the ending value when it exits;
did you know this?
You don't need to compare bool values to true or false.
You could simplify the isAFactor function to return (outer %
inner) == 0;.
You could replace the call to isAFactor with the expression
((outer % inner) == 0).