C++ Prime Number not giving the correct answer [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
#include <iostream>
#include <cmath>
using namespace std;
bool prime(int n);
int main()
{
double i;
while (true)
{
cout << "Enter a number that isn't 0: ";
cin >> i;
if ( i == 0)
break;
if(prime(i))
cout << i << " is prime" << endl;
else
cout << i << " is not prime." << endl;
}
system ("Pause");
return 0;
}
bool prime (int n)
{
int i;
double sqrt_of_n = sqrt(double (n));
for (i = 2; i <= sqrt_of_n; i++)
{
if (int(n) % 1 == 0)
return false;
}
return true;
}
Everytime I run the program, if I input 7, I get that 7 isn't prime. Can someone help me figure out where I messed up?
I have tried changing between double and int for i and n.
If I input 3, it shows prime.
The problem is that it's showing some prime numbers as not prime.

The body of your for loop doesn't use i at all.
In particular, n % 1 is always zero, for any integral n.
Presumably you want to know whether n is divisible by i, but accidentally checked if n is divisible by 1.
You could easily have discovered this mistake yourself by single-stepping in a debugger, and making the various subexpressions into "watch expressions".

Related

I keep getting the same answer, no matter what I put in [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
We're doing an assignment in my computer science class that requires us to find the future value of an investment after "n" number of years that the user inputs. It's written in C++. This is the code as I have it now:
#include <iostream>
using namespace std;
int main() {
int P=1000;
int i=0.0275;
int FV;
int n;
cout << "enter number of years:"<< endl;
cin >> n;
cout << "the future value is:"<< endl;
FV = P*(1+(i*n));
cout << FV << endl;
return 0;
}
I keep ending up with an answer of 1000 no matter what "n" I input. Can someone tell me what's wrong with the code?
#include <iostream>
using namespace std;
int main() {
int P=1000;
float i=0.0275; //float instead of int
float FV; //FV should also be float as it will be storing decimal values
int n;
cout << "enter number of years:"<< endl;
cin >> n;
cout << "the future value is:"<< endl;
FV = P*(1+(i*n));
cout << FV << endl;
return 0;
}
the mistake you have done is the type you assigned to your variables! as int only handles integer values i becomes 0 and your result becomes 1000! use float instead of int for numbers with decimal points!
Datatype of i is int as a result of which your floating point value of i will be rounded of to 0 and you will end up getting the same output doesn't matter what your n value is. Change the datatype of your i and FV varaiable from int to float then your output changes based on what n value you key in

returning a std::list from a function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I've been given an assignment to build the following function template "list primeFactors(unsigned long int n)". The function returns a list of integers of the prime factorization of a natural number. I've created a program that can prime factorization but I'm having issues using a list.
#include <list>
#include <numeric>
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
list<unsigned long int> primeFactors(unsigned long int n)
{
list<unsigned long int> list;
for (unsigned long int i=2; i <=n; i++)
{
while(n % i == 0)
{
n /= i;
//cout << i << " ";
list.push_back(i);
}
return list;
}
}
int main()
{
unsigned long int n;
list<unsigned long int> plist;
cout << "Enter num: " <<endl;
cin>>n;
plist = primeFactors(n);
for(list<unsigned long int>::iterator it=plist.begin(); it != plist.end(); ++it)
{
cout << ' ' << *it;
cout << '\n ';
}
return 0;
}
My program is no longer returning the correct numbers of the factorization and I'm unsure what the issue is.
Any help is appreciated
This likely has nothing to do with returning the list. The problem is you always return it before finishing your iterations:
for (unsigned long int i=2; i <=n; i++)
{
while(n % i == 0)
{
n /= i;
//cout << i << " ";
list.push_back(i);
}
return list; // I think you meant to put this outside the for loop
}
// Probably here is better for the return.
Try using a debugger next time, you will see this issue much more quickly then posting here.
Just return the list outside the for loop
Line return list; is too early. Move it beyond the curly brace.

c++ vector : initializing with cin in a loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I'm new to programming and i have problem with some items
i would appreciate any help
first i started initializing the vector as followed but i couldn't end the loop with Ctrl+Z
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector <double> temps;
double temp;
cout << "Enter a sequence of tempreatures : " << "\n" ;
while (cin >> temp){
temps.push_back(temp);
}
double sum = 0;
for (int i = 0; i< temps.size(); ++i)
sum += temps[i];
cout << "Mean temprature : " << sum / temps.size() << "\n";
sort(temps.begin(), temps.end());
cout << "Median temprature : " << temps[temps.size() / 2];
then i changed the while into this format :
cout << "ENter a sequence of tempreatures ending in 1500 : " << "\n" ;
while (cin >> temp){
if (temp == 1500)
break;
temps.push_back(temp);
}
now i have this error
"vector subscript out of range"
apparently break does not work properly here
what should i do?
Your issue is in the check condition of for loop.
for (int i = 0; i, temps.size(); ++i)
sum += temps[i];
It should be
for (int i = 0; i < temps.size(); ++i)
i, temps.size() will evaluate and then ignore the part before , and are left with temps.size() as check condition which will always be greater than 0 if you push_back at least one element and your loop will never end.You might want to read how ,(comma) works.
If you switch to std::getline into a string instead of std::cin into a double, you can check whether the input is empty:
std::string input;
std::getline(std::cin, input);
while (!input.empty()){
temps.push_back(atof(input.c_str()));
std::getline(std::cin, input);
}
If you also fix the for-loop as mentioned by Gaurav Sehgal, it works fine (Enter all numbers then hit enter without any input).
If you are on windows then you have to do
CTRL + Z
If you are on Unix based(Linux/Mac) then you have to do
CTRL + D
This will give the end of file signal and you will be able to break the loop

Beginning C++: using if else, n--, number [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am struggling to get this program to work. Could someone please look it over to see what is wrong? (The compiler says that sum_positive is not defined in this way.) Also, I have searched this problem and found an answer on here, but I did not see the problem that way and want to avoid plagiarism when I turn in my homework. Thank you!
Write a program that reads in ten whole numbers and that outputs the sum of all the numbers greater than zero, the sum of all the numbers less than zero (which will be a negative number or zero), and the sum of all the numbers, whether positive, negative, or zero. The user enters the ten numbers just once each and the user can enter them in any order. Your program should not ask the user to enter the positive numbers and the negative numbers separately.
Program:
#include <iostream>
using namespace std;
int main()
{
int number, n = 10, sum_positive = 0, sum_negative = 0, sum = 0;
int count = 0, positive_count = 0, negative_count = 0;
cout << "Please enter in 10 whole numbers, one at a time." << endl;
do
{
cout << "Please enter another number." << endl;
cin >> number;
n--;
}
while (n > 0);
if (number >= 0)
{
sum_positive += number;
//positive_count++; count++;
}
else
{
sum_negative += number;
//negative_count++; count++;
}
sum = sum_positive + sum_negative;
cout << sum_postive << endl;
cout << sum_negative << endl;
cout << sum << endl;
return 0;
}
there is a spelling mistake in your code of sum_positive in line (cout << sum_postive << endl;) - you have written sum_postive but you declared sum_positive.
you are running a loop and taking input in the same variable number, so it will overwrite all the inputs and will store only the last value in variable number which user entered. So your sum will always be equal to the last value user entered.
For this you need to use an array.
Example:
int number[10], n=10, sum_positive=0;
do{
cout<<"e`enter code here`nter number:";
cin>>number[n];
n--;
}while(n>0);
now for sum also you need to use an loop.
If you do not know about an array, study about it how to use it.

If inside while error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
int main()
{
vector<int>numbers;
int numb = 0;
int i = 0;
int j = i - 1;
while (cin >> numb)
{
if (numb == numbers[j]) HERE IS THE PROBLEM!*
{
cout << "Numbers repeated\n";
}
numbers.push_back(numb);
cout << "numbers[" << i << "] = " << numbers[i] << endl;
++i;
}
/*** I don't understand why a exception, run time error, break or whatever it names.....................................................
On the first iteration through the loop, j is -1. Accessing numbers[-1] is undefined behavior because the index is outside the bounds of the vector.
Indeed, accessing any index is out of bounds until you put something in the vector, so you cannot index numbers at all until you have called push_back on it at least once.
This code will display the message if the user enters a number already in the vector:
while (cin >> numb) {
vector<int>::iterator found = std::find(numbers.begin(), numbers.end(), numb);
if (found == numbers.end()) {
cout << "Numbers repeated" << endl;
}
// If you don't want duplicate numbers in the vector, move this statement
// into an "else" block on the last "if" block.
numbers.push_back(numb);
}
This code on the other hand will only display the message when a number was the same as the last number entered, that is, if sequential numbers are the same:
while (cin >> numb) {
if (!numbers.empty() && numb == numbers.back()) {
cout << "Numbers repeated" << endl;
}
numbers.push_back(numb);
}
You need to initialize your numbers vector with initial data, or check to make sure j is withing in vector size. A vector is essentially an array, and like any array, you cannot go out of bounds.
if (j < numbers.size() && numb == numbers[j]) HERE IS THE PROBLEM!*
{
cout << "Numbers repeated\n";
}