I tried making a program to find the lowest common multiple of any two numbers. I have gotten most of the way there but my program prints all of the common multiples from 1-1000000 instead of just the first one. How do I make it print only the first one
?
#include <iostream>
using namespace std;
int main() {
cout << "Find the lowest common multiple of two numbers, just enter them one after the other" << endl;
int firstNum;
int secondNum;
cin >> firstNum;
cin >> secondNum;
int i;
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
}
}
system("pause");
return 0;
}
You can add a break to end a loop. In your case, you want to add it at the end of your if statement:
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
break;
}
}
Your problem is a break statement as others have mentioned.
But a better solution: lcm is standardized in C++17! So you can just do:
cout << lcm(firstNum, secondNum) << endl;
If you don't have access to C++17 yet this is already available in the namespace experimental: http://en.cppreference.com/w/cpp/experimental/lcm
After finding the first one you need to leave from for loop, that is why it keeps printing other values.
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
break;
}
}
Related
While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum = 0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout << "Please enter a series of numbers, press (Q or q) to process: ";
cin >> num;
if (cin.fail())
{
cin.clear();
cin >> var;
if (var != "Q" && var != "q")
{
cout << "Invalid input, try again" << endl;
}
}
if (num > largest)
{
largest = num;
}
if (num < smallest)
{
smallest = num;
}
if (num == 0 || num == 1)
{
prime = prime;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
j = 1;
break;
}
}
if (j == 0)
{
prime++;
}
}
sum += num;
cout << "The corresponding element for the cumulative total sequence is: " << sum << endl;
cin.ignore(sum, '\n');
} while (var != "Q" && var != "q");
cout << endl;
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "How many prime numbers? " << prime << endl;
cout << "Have a great day!" << endl;
}
Here is an example of the program being run.
Program example
The smallest number here should be 8, and the issue is that it begins at 0. The same thing with the largest number.
Program example #2
Your loop is testing the "num" variable even if the user inputs q or Q, adding an else statement else break; after the if (var != "Q" && var != "q") will fix it.
For the future, always keep in mind that when the "if" function fails, it will move on to the next line, if you need to to not execute, you either need to break out of the loop or change the structure of your code.
Trying to make a calculator that calculates values in an array based on input from user. But the first value in the array is always 0 when I leave 'p undefined or p = 1 will have give me the same problem. It should be whatever the user enters for the first value and so on.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
The sum should be 3 not 4.
How many numbers are you working with today?
2
Enter number 1:
1
What would you like the numbers to do: (+ - / *)
+
Enter number 2:
2
What would you like the numbers to do: (+ - / *)
+
4
The program is invalid and has undefined behavior.
For starters variable length arrays is not a standard C+ feature
int p = 1, y = 0;
double sum = 1;
int many[p];
And in any case you defined an array with one element. So the only valid index to access elements of the array is 0.
Even in the first statement that uses the array
cin >> many[p];
it is accessed outside its bounds.
You should use the standard class template std::vector. Or as in fact you are dealing with one value then there is even no sense to use a container, Define a scalar object instead of the array.
The initial value of the sum is 1, that's why it is adding 1 more. We can't keep it 0 either, because then it will mess up the '*' and '/' cases.
I have added the initial sum value for all the cases.
Also, I would suggest you, to use switch cases instead of if, else statements.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
if (y == 0) {
sum = 0;
}
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
if (y == 0) {
sum = 0;
}
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
if (y == 0) {
sum = 1;
}
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
if (y == 0) {
sum = 1;
}
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
There are a lot of things here that don't make sense.
You are starting with sum = 1. this is why the value is always +1
many is an array of size 1, can be changed to single int.
you are accessing many[p] which is many[1] which is out of bounds. you can only access many[0]
the rest I leave it to you to find,
I'm currently taking C++ and one my assignments is to create a program that checks if the number is a prime number correctly handle the invalid
integer inputs. In addition, user should be able to test as many integers as he or she wants in a single run. In other words, the program should not end unless the user tells you to.
I understand the prime number check part but I cannot figure out to implement the "test as many integers as you want in a single run and handling invalid input"
Any comments and edits to the code would be greatly appreciated. Thank you!
using namespace std;
int main () {
int num, i, count = 0;
cout << "Enter the number to be checked : ";
cin >> num;
if (num == 0)
{
cout << "\n" << num << " is not prime";
exit(1);
}
else {
for(i=2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
cout << "\n" << num << " is not prime.";
else
cout << "\n" << num << " is prime.";
return 0;
}
Here is the code that you can try. After input the number, the program will ask whether you want to continue or not by inputting y or n.
If the user input y, the program will keep looping and ask the question again otherwise it will break the loop.
Last note : don't use using namespace std (bad habit)
#include <iostream>
#include <string>
int main () {
int num, i, count = 0;
char flag;
while(1)
{
std::cout << "Enter the number to be checked : ";
std::cin >> num;
if (num == 0)
{
std::cout << "\n" << num << " is not prime";
}
else {
for(i=2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
std::cout << "\n" << num << " is not prime."<<std::endl;
else
std::cout << "\n" << num << " is prime."<<std::endl;
std::cout <<"Do you want to continue? [y/n]";
std::cin >> flag;
if (flag == 'n')
break;
}
return 0;
}
Of course, you can change the y/n to another char or string or int or whatever you want
I am solving the following simple problem(on one of OnlineJugde sites which is in Russian, so I won't give a link here:). It is easier to state the problem via an example than definition.
Input:
10 // this is N, the number of the integers to follow
1 1 1 2 2 3 3 1 4 4
Output:
3 times 1.
2 times 2.
2 times 3.
1 times 1.
2 times 4.
Constraints:
All the numbers in the input(including N) are positive integer less than 10000.
Here is the code I got Accepted with:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
while(n --> 0) // do n times
{
cin >> currentNumber;
if(currentNumber != prevNumber)
{
if(currentCount != 0) //we don't print this first time
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else //if(currentNumber == prevNumber)
{
++currentCount;
}
}
cout << currentCount << " times " << prevNumber << "." << endl;
}
Now here's my problem. A little voice inside me keeps telling me that I am doing this line two times:
cout << currentCount << " times " << prevNumber << "." << endl;
I told that voice inside me that it might be possible to avoid printing separately in the end. It told me that there would then be perhaps way too many if's and else's for such a simple problem. Now, I don't want to make the code shorter. Nor do I want do minimize the number of if's and else's. But I do want to get rid of the special printing in the end of the loop without making the code more complicated.
I really believe this simple problem can be solved with simpler code than mine is. Hope I was clear and the question won't be deemed as not constructive :)
Thanks in advance.
i came up with this. no code duplication, but slightly less readable. Using vector just for convenience of testing
EDIT my answer assumes you know the numbers ahead of time and not processing them on the fly
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(3);
numbers.push_back(1);
numbers.push_back(4);
numbers.push_back(4);
for (int i=0; i<numbers.size(); i++)
{
int count = 1;
for (int j=i+1; j<numbers.size() && numbers[i] == numbers[j]; i++, j++)
{
count++;
}
cout << count << " times " << numbers[i] << "." << endl;
}
My version: reading the first value as a special case instead.
#include <iostream>
int main()
{
int n;
std::cin >> n;
int value;
std::cin >> value;
--n;
while (n >= 0) {
int count = 1;
int previous = value;
while (n --> 0 && std::cin >> value && value == previous) {
++count;
}
std::cout << count << " times " << previous << ".\n";
}
}
Run your loop one longer (>= 0 instead of > 0), and in the last round, instead of reading currentNumber from cin, do currentNumber = lastNumber + 1 (so that it's guaranteed to differ).
slightly more CREATIVE answer, this one does not make assumption about input being all known before the start of the loop. This prints the total every time, but makes use of \r carriage return but not line feed. A new line is inserted when a different number is detected.
int prev_number = -1;
int current_number;
int count = 0;
for (int i=0; i<numbers.size(); i++)
{
current_number = numbers[i];
if (current_number != prev_number)
{
count = 0;
cout << endl;
}
count++;
prev_number = current_number;
cout << count << " times " << numbers[i] << "." << "\r";
}
only problem is that the cursor is left on the last line. you may need to append cout << endl;
I think this will work:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
int i = 0;
while(i <= n)
{
if(i != n) cin >> currentNumber;
if(currentNumber != prevNumber || i == n)
{
if(currentCount != 0)
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else
{
++currentCount;
}
i++;
}
}
I would use a for loop, but I wanted to stay as close to the original as possible.
I am trying to make a program that determines if the number is prime or composite. I have gotten thus far. Could you give me any ideas so that it will work? All primes will , however, because composites have values that are both r>0 and r==0, they will always be classified as prime. How can I fix this?
int main()
{
int pNumber, limit, x, r;
limit = 2;
x = 2;
cout << "Please enter any positive integer: " ;
cin >> pNumber;
if (pNumber < 0)
{
cout << "Invalid. Negative Number. " << endl;
return 0;
}
else if (pNumber == 0)
{
cout << "Invalid. Zero has an infinite number of divisors, and therefore neither composite nor prime." << endl;
return 0;
}
else if (pNumber == 1)
{
cout << "Valid. However, one is neither prime nor composite" << endl;
return 0;
}
else
{
while (limit < pNumber)
{
r = pNumber % x;
x++;
limit++;
if (r > 0)
cout << "Your number is prime" << endl;
else
{
cout << "Your number is composite" << endl;
return 0;
}
}
}
return 0;
}
Check out http://en.wikipedia.org/wiki/Prime_number and http://en.wikipedia.org/wiki/Primality_test
The simplest primality test is as
follows: Given an input number n,
check whether any integer m from 2 to
n − 1 divides n. If n is divisible by
any m then n is composite, otherwise
it is prime.
#include <iostream>
#include <math.h>
// Checks primality of a given integer
bool IsPrime(int n)
{
if (n == 2) return true;
bool result = true;
int i = 2;
double sq = ceil(sqrt(double(n)));
for (; i <= sq; ++i)
{
if (n % i == 0)
result = false;
}
return result;
}
int main()
{
std::cout << "NUMBER" << "\t" << "PRIME" << std::endl;
for (unsigned int i = 2; i <= 20; ++i)
std::cout << i << "\t" << (IsPrime(i)?"YES":"NO") << std::endl;
std::cin.get();
return 0;
}
bool check_prime(unsigned val) {
if (val == 2)
return true;
// otherwise, if it's even, it's not prime.
if ((val & 1) == 0)
return false;
// it's not even -- only check for odd divisors.
for (int i=3; i*i<=val; i+=2)
if (val % i == 0)
return false;
return true;
}
with respect ur code u didn't check if i enter 2 what will be happened,
and also u didn't return any thing if it is prime....thats why it is always returning prime in spite the number is composite .
here is the code below =>
#include<iostream>
using namespace std;
int main(){
int pNumber, limit, x, r;
limit = 2;
x = 2;
cout << "Please enter any positive integer: " ;
cin >> pNumber;
if (pNumber < 0){
cout << "Invalid. Negative Number. " << endl;
return 0;
}
else if (pNumber == 0){
cout << "Invalid. Zero has an infinite number of divisors, and therefore neither composite nor prime." << endl;
return 0;
}
else if (pNumber == 1){
cout << "Valid. However, one is neither prime nor composite" << endl;
return 0;
}
else if (pNumber == 2){
cout << " Your number is prime" << endl;
return 0;
}
else{
while (limit < pNumber){
r = pNumber % x;
x++;
limit++;
if (r > 0){
cout << "Your number is prime" << endl;
return 0;
}
else{
cout << "Your number is composite" << endl;
return 0;
}
}
}
return 0;
}
For one thing, you'll want to break out of your loop when you find some x where pNumber % x == 0. All you need to do is find one factor of pNumber greater than 1 and less than pNumber to prove it's not prime -- no point in searching further. If you get all the way to x = pNumber without finding one, then you know pNumber is prime. Actually, even if you get to the square root of pNumber without finding one, it's prime, since if it has a factor greater than that, it should have a factor less than that. Make sense?
I don't know what you have been taught thus far, but my discrete mathematics teacher was a fan of the Miller-Rabin test. It is a pretty accurate test that is very easy to code, within a few base tests you have a very negligible chance that you have a Carmichael Number. If you haven't gotten that far in your studies I would just stick to some basic division rules for numbers.
Simplest method is for a given number n , if it is perfectly divisible with any number between 2 to sqrt(n), its a composite, or else its prime
Hi i have done this that also without using math.h header file....Have used turboc compiler.
Following program checks whether the number is prime or composite.
#include<iostream.h>
#include<conio.h>
class prime
{
int a;
public:
void check();
};
void prime::check()
{
cout<<"Insert a number";
cin>>a;
int count=0;
for(int i=a;i>=1;i--)
{
if(a%i==0)
{
count++;
}
}
if(count==1)
{
cout<<"\nOne is neither prime nor composite";
}
if(count>2)
{
cout<<"\nThe number is composite " ;
}
if(count==2)
{
cout<<"\nThe numner is prime";
}
}
void main()
{
clrscr();
prime k;
k.check();
getch();
}