Prime-testing program not working - c++

#include "stdafx.h"
#include "math.h"
#include <string>
#include <iostream>
using namespace std;
int main ()
{
int x;
cout << "Enter a number." << endl;
cin >> x;
int y = 1;
int i = 0;
while (i == 0 && y < sqrtf(x))
{
if (fmodf(x,y) == 0)
{
i = 1;
}
else
{
i = 0;
}
y++;
if (i == 1)
{
cout << "Your number is prime." << endl;
}
else
{
cout << "Your number is composite." << endl;
}
}
return 0;
}
This is a code I created to test for primes. After sorting out several debugging issues I was able to run it.
It opened the command window, read 'Enter a number' and closed itself the second I entered a number.
Help?

You have to:
close the while loop in the correct place
change the if (i == 1) condition (i==1 means x is divisible by some y)
start with y = 2 (every number is divisible by one)
include sqrtf(x) in the loop (y <= sqrtf(x) or 15, 25, 35... are primes).
So:
int main()
{
int x;
cout << "Enter a number." << endl;
cin >> x;
int y = 2; // <-- changed
int i = 0;
while (i == 0 && y <= sqrtf(x)) // <-- changed
{
if (fmodf(x,y) == 0)
{
i = 1;
}
else
{
i = 0;
}
y++;
} // <-- moved here
if (i == 0) // <-- changed
{
cout << "Your number is prime." << endl;
}
else
{
cout << "Your number is composite." << endl;
}
return 0;
}
works (more or less...).
Anyway:
don't use using namespace std; (Why is "using namespace std" considered bad practice?)
\n should be your default ("\n" or '\n' or std::endl to std::cout?)
y and x are integers so you can use % instead of fmodf
avoid premature pessimization: prefer preincrement, only use postincrement if you're going to use the original value
else { i = 0; } is superfluous
you can change y < sqrtf(x) with y * y <= x (and you don't need math.h anymore) or find square root of number then start the loop
Somewhat better (but far from perfect):
#include <cmath>
#include <iostream>
int main()
{
int x;
std::cout << "Enter a number.\n";
std::cin >> x;
int square_root = std::sqrt(x);
int y = 2;
int i = 0;
while (i == 0 && y <= square_root)
{
if (x % y == 0)
i = 1;
++y;
}
if (i == 0)
std::cout << "Your number is prime.\n";
else
std::cout << "Your number is composite.\n";
return 0;
}
Now:
input validation, i.e. check for bad input values (How to check if input is numeric in C++)
special cases checking (is the number one a prime number?)
a bool would express your intentions better than int i;
improve the algorithm (Determining if a number is prime, Which is the fastest algorithm to find prime numbers?, Primality tests)

Related

Why is my code stopping prematurely? what have i done wrong?

I'm just starting so I'm trying to write a program which determine if a number is positive or negative.
#include <iostream>;
int step_function(int x) {
int result = 0;
if (x > 0)
result = 1;
else if (x < 0)
result = -1;
else
result = 0;
return result;
}
using namespace std;
int main() {
int num;
cout<< "please enter number : ";
cin >> num;
int a = step_function(num);
if (a == 1)
printf("%d is positive", num);
else if (a == -1)
printf("%d is negative", num);
else
printf(" it is zero");
return 0;
}
There is a few things you should do:
First things first you should get yourself a Good Book for C++.
Second thing is read why using namespace std; is a bad idea.
Lastly here is your code fixed. You needed to remove the semicolon as well as removing the printf(). I also removed the using namespace std; which made it more readable.
#include <iostream>
int step_function(int); //Function prototype
int main() {
int num;
std::cout << "please enter number : ";
std::cin >> num;
int a = step_function(num);
if (a == 1)
std::cout << num << " is postive";
else if (a == -1)
std::cout << num << " is negative";
else std::cout <<" it is zero";
return 0;
}
int step_function(int x)
{
int result = 0;
if (x > 0) result = 1;
else if (x < 0) result = -1;
else result = 0;
return result;
}
Don't use semicolon after #include <iostream>.
I think for C++ cout is more standard whereas printf is from C.
You can also include printing of the text in the step_function. Also, it's better to use braces {} after if and else statements for clarity especially if the code becomes complex.
#include <iostream>
using namespace std;
void step_function(int x) {
if (x > 0) {
cout << x << " is positive" << endl;
}
else if (x < 0) {
cout << x << " is negative" << endl;
}
else {
cout << "it is zero" << endl;
}
}
int main() {
int num;
cout<< "please enter number : ";
cin >> num;
step_function(num);
return 0;
}

why do i have to add a new variable in this code

I was trying to write a code that takes two numbers as a input and change the numbers into words in certain rules.
Below is the code I wrote at first, but whatever input I put in, the loop starts from x=0.
#include <iostream>
int main() {
string nums[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
int x,y;
cin >> x;
cin >> y;
for (int x = x; x <= y; x++){
if (x <= 9){
cout << nums[x] << "\n";
}
else if (x % 2 == 0){
cout << "even" << "\n";
}
else {
cout << "odd" <<"\n";
}
}
return 0;
}
Below is the second code I wrote and it worked as I wanted to.
#include <iostream>
int main() {
string nums[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
int x,y;
cin >> x;
cin >> y;
for (int i = x; i <= y; i++){
if (i <= 9){
cout << nums[i] << "\n";
}
else if (i % 2 == 0){
cout << "even" << "\n";
}
else {
cout << "odd" <<"\n";
}
}
return 0;
}
I found out that if I add a variable, it works as what I wanted too. I found the solution but I don't know why I have to add a variable and why the first one always starts from x=0.
In first sample that you provided you defined a local variable(x) as same name in outer block:
for (int x = x; x <= y; x++)
In fact shadowing of variable take place here and c++ hide the declaration of variable of outer block with same name in nested block.

C++ if statement not printing desired output

Problem is with the if statment inside the while loop. It is not printing the desired output. The else if statement and the else statement seem to work fine
Any help is appreciated
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
while (sum < input) {
// This is the if statement giving me problems
if (input == 1) {
exponent += 1;
sum = 3;
}
// This else if statement seems to work fine
else if (input == 3) {
exponent += 2;
sum = 9;
}
else {
exponent++;
sum *= base;
}
}
// Print output
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
Your logic is wrong (and I have to say a bit bizarre).
If the input is 1 then while (sum < input) is not true and so you never reach your if (input == 1) statement.
REALIZED my mistake. i just moved the if and else if statement to outside the loop
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
if (input == 1) {
exponent += 1;
sum = 3;
}
else if (input == 3) {
exponent += 2;
sum = 9;
}
while (sum < input) {
exponent++;
sum *= base;
}
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
If I understood the objective right from the comments, if conditions are not required. Just replace the condition and simplify the while loop as follows:
while (sum <= input) {
exponent++;
sum *= base;
}
Write a C++ program that asks the user for an integer. The program
finds and displays the first power of 3 larger than the input number
using while
You should probably calculate the answer instead of looping.
#include <iostream>
#include <cmath>
int main() {
int input;
std::cout << "input: ";
std::cin >> input;
int x = 0;
/*
3^x == input
ln(3^x) == ln(input)
x*ln(3) == ln(input)
x == ln(input)/ln(3)
*/
// calculate x = ln(input)/ln(3), round down and add 1
if(input > 0) x = std::floor(std::log(input) / std::log(3.)) + 1.;
std::cout << "answer: 3^" << x << " == " << std::pow(3, x) << "\n";
}

Copying from input to the output text file

Hi guys here is my functional code but it does not works properly it should do read numbers from input.txt and count the sum of even,odd numbers in each line then conjunction of prime numbers( which does correctly) and also copy all numbers which are prime to the output.txt
here is my code the problem is : it copies also numbers which are not prime numbers. Thanks a lot !!!
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream read;
read.open("input.txt");
ofstream write;
write.open("output.txt");
string line;
int even, odd, primeXprime;
if(read.fail())
cout << "Cant open input.txt" << endl;
int x, p = 0;
if(read.is_open())
{
while(read, line)
{
even = odd = 0;
primeXprime = 1;
istringstream sRead(line);
while(sRead >> x)
{
if(x % 2 == 0)
even += x;
if(x % 2 != 0)
odd += x;
for(int i = 2; i <= x; i++)
{
if(x % i == 0)
p++;
if(p == 2)
{
primeXprime *= x;
write << x << " ";
p = 0;
}
else
break;
}
}
cout << "Sum of even numbers are: " << even << endl;
cout << "Sum of odd numbers are: " << odd << endl;
cout << "Sum of prime numbers are: " << primeXprime << endl;
cout << endl;
}
read.close();
write.close();
system("pause");
return 0;
}
}
Problem is with your Primality Testing algorithm , You cannot determine a number is prime or not until you divide it by all the numbers in the range [2,Sqrt(n)]
In line "if(p == 2)" you are assuming that it wont be divided by any number later on in the range .
Replace your entire for loop by
for(int i = 1; i < x; i++)
{
if(x % i == 0)
p++;
}
if(p < 2)
{
primeXprime *= x;
write << x << " ";
}
p = 0;

cannot achieve desired output (cout) from a C++ loop

thanks to your help last night I was able to get my program computing my input properly, but now I am have trouble formatting my output properly. This is the problem:
My program should only print "is prime" on lines with prime numbers. But it prints on ever line like this:
http://oi42.tinypic.com/30igbvq.jpg
I cannot for the life of me figure out why it is doing this, all of my functions should work.
Stack I need your help again!
#include <iostream>
using namespace std;
void primecheck(int x); // proto
void countr(int rnm, int lnm); // proto
void prime(int x) // this function finds the prime factors of a number.
{
int lastr = 2;
int count = 0;
while (lastr < x)
{
if (x % lastr == 0)
{
cout << x << " " << lastr << "*";
x /= lastr;
}
else
++lastr;
}
primecheck(x); // calls to check if number is prime, "Is prime"
}
void console(int rnum, int lnum) // this prompts the user for two numbers then stores the answers
{
cout << "please enter two numbers ";
cin >> rnum;
cin >> lnum;
countr(rnum, lnum);
}
void countr(int rnm, int lnm) // this function loops the prime function until all the numbers are computed
{
int i = rnm;
do{
prime(i);
i++;
} while (i <= lnm);
return;
}
int main() // main, calls console then pauses when finished
{
int e = 0;
int r = 0;
console(e, r);
system("PAUSE");
}
void primecheck(int x) // checks to see if then number is prime. if counter is equal to 2 than number is prime.
{
int counting = 0;
for (int a = 1; a <= x; a++)
{
if (x %a == 0)
{
counting++;
}
}
if (counting == 2)
{
cout << x << " is prime " << endl;
}
else
{
cout << x << endl;
}
}
You're using a /= operator in prime(). That's an assignment operator and is modifying the value of x, making x always prime whenever primecheck() is called.