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;
Related
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";
}
#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)
I have to write out a list of prime numbers from 1-100, using a function we have previously wrote, to a file. The commented out part isn't anything related; it's just the previous code we used for the function. I don't know exactly what's going on because the file isn't even being created, and the part inside the for loop is executing with just 2's, 100 times.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
int p = 2;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
isPrime(p);
cout << p << endl;
outputFile << p << endl;
}
outputFile.close();
cout << "You should now have the file." << endl;
/* int n;
int counter = 0;
int p = 2;
cout << "Welcome to prime counter. " << endl;
cout << "Which prime number would you like? ";
cin >> n;
while (counter < n) {
if (isPrime(p)) {
counter++;
}
p++;
}
p = p - 1;
cout << "Prime number " << n << " is " << p << "." << endl;
*/
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
Could someone please explain what I'm doing wrong here, and why it isn't even creating the file?
You initialize p at the top with 2. You should be calling isPrime with i instead.
You're getting 2s because you're printing out and storing p, but the loop is going over i.
Here is the updated code. Upon research I did find where it was saving the files, and there are instances of it just not working at all. However, This code runs and does give me everything I need it to.. Thank you for the tips, and I appreciate the very.... constructive feedback.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
if (isPrime(i)) {
outputFile << i << endl;
}
}
outputFile.close();
cout << "You should now have the file." << endl;
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
I'm taking my first programming course and am new to this forum. Any help will be greatly appreciated! For one of my class assignments I had to write a program that would find the factors of a given number, I've got the program up and running but one of the stipulations is that the output must be displayed four to a line and that's where I'm running into trouble. I've read around on some other forums as well as here but I guess I'm not grasping what I would have to do in my particular case.
Here's my code as is:
#include <iostream>
using namespace std;
int main(){
int n;
while (cout << "Please enter a number: " && !(cin >> n) || (n < 0.0) || cin.peek() != '\n')
{
cout << "Input must be a positive number!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
for (int i=2; i <= n; i++)
{
while (n % i == 0)
{
n /= i;
cout << "*" << i;
}
}
cout << endl;
system ("PAUSE");
return 0;
}
You're going to need to add a counter outside the loop.
//int counter = 0;
for (int i=2; i <= n; i++)
{
while (n % i == 0)
{
n /= i;
cout << "*" << i;
}
}
The counter will need to keep track of how many entries have been printed.
Once you have seen 4 entries printed:
print an extra newline
and set the counter back to 0
You may use the following:
void display_factors(std::size_t n, std::size_t factor_by_line)
{
const char* sep = "";
std::size_t count = 0;
std::cout << n << " = ";
for (int i = 2; i <= n; ++i) {
while (n % i == 0) {
n /= i;
if (count == factor_by_line) {
std::cout << std::endl;
count = 0;
}
++count;
std::cout << sep << i;
sep = " * ";
}
}
std::cout << std::endl;
}
Live Demo
I spent a day on this code for count even and zero and odd numbers
From long datatype I used a function to send data. Here is the code
#include <iostream>
using namespace std;
void digitCount(long long int &num);
int main ()
{
long long int num;
cout <<"Enter any No. " <<endl;
cin >>num;
cout <<endl;
digitCount(num);
return 0;
}
void digitCount(long long int &num)
{
int e = 0, z = 0, o = 0, x = 0;
for (int i = 0; i <= num; i++)
{
x= num % 10;
if(x == 0)
{
++z;
num = num / 10;
}
else if(x%2==1)
{
++o;
num = num / 10;
}
else
{
++e;
num = num / 10;
}
}
cout << "No of zeros Digits = " << z<< endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
the problem is when I count odd numbers there is a number missed
for example when i input : 12345
the result is
no of even : 2
no of odd : 2 (should be 3)
no of zero : 0
and here the question :
Write a function that takes as parameter an integer (as a long value) and returns the number of odd, even, and zero digits. Also write a program to test your function. Use pass by reference method.
Instead of the for loop you should use:
while (num > 0)
You're constantly changing num and when it gets to 1 (in your 12345 example), i is at 3. I also modified your digitcount to demonstrate some decent formatting for readable code.
void digitCount(long long int &num) {
int e(0), z(0), o(0), x(0);
while (num > 0) {
x = num % 10;
if (x == 0) {
z++;
}
else if (x % 2 == 1) {
o++;
}
else {
e++;
}
num /= 10;
}
cout << "No of zeros Digits = " << z << endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
If you believe this solves your problem && is the best answer, please click the checkmark next to this answer. Thanks