I want to ask the user for an integer, and print the prime factors.
Example: User enters 100, program displays 2 2 5 5
So far I have the following:
#include <iostream>
using namespace std;
void factors(int n){
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
cout << z;
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{cout << n << "\n";}
}
int main()
{
int x;
cout << "Input positive integer greater than 1: ";
cin >> x;
factors(x);
cout << "The result: " << x;
return 0;}
My question is how do I get my main function to communicate with the factors procedure. I run the program, I get the message asking for input, I input 12, I get the message "The result" but with a number of 25, and also 12, the number that the user input. it's like the program is avoiding my factors(int n) procedure. Help with the syntax please?!?
My issue is with the syntax I think.
Because I found the following function to help with listing prime factors:
Finding prime factors
-user44810
define factors(n)
z = 2
while (z * z <= n)
if (n % z == 0)
output z
n /= z
else
z++
if n > 1
output n
Thank you!!!
Try this
#include <iostream>
#include <vector>
using namespace std;
vector<int> factors(int n){
vector<int> result;
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
result.push_back(z);
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
result.push_back(z);
return result;
}
int main()
{
int x;
cout << "Input positive integer greater than 1: ";
cin >> x;
vector<int> result_factors = factors(x);
cout << "The result: ";
for (int i: result_factors)
cout << "i ";
cout << endl;
return 0;
}
I changed your factor() function to output nothing on cout but saving the factors in a vector and returning it. In the main function, iterate over the result vector and print the values to cout.
So the biggest issue is that there is a missing brace at the end of your factors function. you need to add another brace after the if (n > 1) brace. Also, there is a missing semicolon at the end of the last cout that will throw an error.
Another issue that won't prevent the code from running is that when you print "The result: " << x you will be giving the same value as the user input.
If you want your main function to print out the result from factors() at that spot, then the function needs to return the data instead of printing it. To fix this, the factors function can be made to return a string with the output you want:
//return a string with the output
string factors(int n){
//create a string to save the output to
string factorlist = "";
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
//append z to the end of the string and add a space to make it easier to read
factorlist+=to_string(z)+" ";
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{
//append n to the end of the string and add a newline
factorlist+=to_string(n)+"\n";
}
//output the string factorlist to wherever the function was called from
return factorlist;
}
then on the lines that look like:
factors(x);
cout << "The result: " << x
Should be:
cout << "The result: " << factors(x);
Currently, you are just printing out the value of x that the user input. If you want to save the value of factors(x) you would need to set a variable equal to it like this:
string FactorsResult = factors(x)
And then print it; or, as in the corrected code above, just print it directly in the cout statement.
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 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
I am trying to write a program that will approximate e^x using taylor series as follows:
I created a function that will do the summation, taking in n (number of times to sum) and x (the exponent) and another function that takes in a number and returns its factorial. Pretty simple stuff I think. The problem I'm having is when I input a fractional x first (for instance, .5, 6) the program just hangs. If I first input something like (3, 6) and then after that calculation, I input (.5, 6)I will get an infinite loop. If the x I input is not a fraction, I can do the calculation as many times as I like.
I feel that it must have something to do with my call to the pow() function. I think I'm using it correctly (pow(double, int)) but does it not take fractions or something? I don't understand.
Here's my code:
double taylorSeries (double x, int n, double &error)
{
double sum = 0;
for (int i=0; i <= n; i++)
sum += (pow (x, i))/(factorial (i));
error = (fabs(exp(x) - sum));
return sum;
}
long factorial(int n)
{
long factorial=0;
for (int i = 0; i <= n; i++){
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
}
return factorial;
}
And then the call to the taylorSeries function in main looks like this:
cout << "please enter x and n: ";
cin >> x >> n;
cout << "taylor series sum = " ;
cout << taylorSeries (x, n, error) << endl;
//cout << "error = " << error;
Can someone help me figure out why this isn't working?
Never mind some of the inefficiencies of your algorithm, the most likely cause for your function seemingly fail to return is a bad parsing of x and thus n not getting set at all, which means it could hold any random value.
Your line:
cin >> x >> n;
If it fails to parse into x properly then it will not attempt to parse the next number because the input stream will be in an error state.
If n has not been initialised it could hold any value which might in reality be an extremely big integer. Thus your algorithm appears not to ever return.
int main()
{
double x = 0.0;
int n = 0;
double error = 0;
cout << "please enter x and n: ";
cin >> x >> n;
if( cin )
{
cout << "taylor series sum, x=" << x << " n=" << n << " : ";
cout << taylorSeries (x, n, error) << endl;
cout << "error = " << error;
}
else
{
cerr << "invalid input" << endl;
}
}
For a more efficient algorithm:
double taylorSeries (double x, int n, double &error)
{
double sum = 1;
double xpow = x; // would start at 1 but we have implemented exponent of 0
double fact = 1;
for (int i=1; i <= n; i++)
{
fact *= i;
sum += xpow / fact;
xpow *= x;
}
error = fabs(exp(x) - sum);
return sum;
}
Your factorial function is technically correct until the point where it will overflow.
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.