C++ factorial function not working - c++

Can someone please help me understand why this code isn't working properly? I know it's very close and I think that I'm just overlooking something. Any help is appreciated. Here is what I have so far:
#include <iostream>
#define TEST_ARRAY_SIZE 4
long int factorial(int num);
long int factorial(int num){
for(unsigned int i = 1; i <= num; i++) {
num *= i;
}
return num;
}
int main() {
int test[TEST_ARRAY_SIZE] = {1, 2, 5, 7};
for (unsigned int i = 0; i < TEST_ARRAY_SIZE; i++) {
std::cout << "Factorial of " << test[i] << " is " << factorial(test[i]) << std::endl;
}
return 0;
}

You should move return num; outside the loop. As it is now, control always return after the first number is multiplied.
-- the correct code --
long int factorial(int num){
long int res = 1;
for(unsigned int i = 1; i <= num; i++) {
res *= i;
}
return res;
}

The body of the factorial function is not correct. You can use a recursive method to compute the factorial of a specific number. The corrected program of your version is below:
#include <iostream>
#define TEST_ARRAY_SIZE 4
long int factorial(int num);
int main() {
int test[TEST_ARRAY_SIZE] = {1, 2, 5, 7};
for (unsigned int i = 0; i < TEST_ARRAY_SIZE; i++) {
std::cout << "Factorial of " << test[i] << " is " << factorial(test[i]) << std::endl;
}
return 0;
}
long int factorial(int num){
if (num == 1)
return num;
else
return num * factorial(num-1);
}

That's only part of the problem; it's a case in which proper indentation would make the bug apparent in an instant.
In addition to that, why are you using num inside the loop? You should leave it as-is and declare a new variable to compound and return the result.
long int factorial(unsigned int num) {
int x = 1;
for(unsigned int i = 1; i <= num; i++) {
x *= i;
}
return x;
}
Other things to note:
You shouldn't be using a #define; you should declare a const instead.
You're comparing an unsigned against a signed in the factorial() for loop.

Related

Using a Factorial Function on an Array in C++

Im trying to get my factorial function to go through all the numbers in my array and give me the result but I keep getting an error message. Any idea what im doing wrong? Here is my code:
#include <iostream>
#include "Recursion.h"
int factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
int main()
{
int my_list[5] = {2, 4, 6, 8, 10};
for(int i = 0; i < 5; ++i)
{
int b = factorial(my_list[i]);
std::cout << b << std::endl;
}
return 0;
}
Your function is designed to take a single integer, and not an array. Iterate over the array, and call the method on each int within the array
for(int i = 0; i < 5; ++i)
{
int b = factorial(my_list[i]);
std::cout << b << std::endl;
}

Sieve of Eratosthenes not working beyond 200,000

My C++ program to calculate all the prime numbers using sieve of Eratosthenes method stops after 200,000. But I need to calculate the primes up to 2 million. Help would be appreciated if someone could tell me where I went wrong with my code.
#include <iostream>
#include<math.h>
using namespace std;
void isprime(long long int prime[],long int n)
{
for(long long int i=0;i<=n;i++)
{
prime[i]=1;
}
prime[0]=prime[1]=0;
for(long long int i=2;i<=sqrt(n);i++)
{
if(prime[i]==1)
{
for(long long int j=2;i*j<=n;j++)
prime[i*j]=0;
}
}
for(long long int i=0;i<=n;i++)
{
if(prime[i]==1)
cout<<i<<endl;
}
}
int main()
{
long long int n;
cout<<"enter number";
cin>>n;
long long int prime[n+1];
isprime(prime,n);
return 0;
}
Since each sieve element contains only a 0 or 1, there is no need to use a long long int to store each one. std::vector<bool> potentially uses 1 bit per element and thus is optimal for memory efficiency.
Here is your code with a very few modifications to use a std::vector<bool>. Since some bit manipulation is required to get and set individual elements, this version may be slower than code which uses one byte or int per sieve element. You can benchmark various versions and decide the right trade-off for your needs.
#include <cmath>
#include <cstddef>
#include <exception>
#include <iostream>
#include <string>
#include <vector>
// returns the number of primes <= n
long isprime(long n) {
std::vector<bool> prime(n + 1);
for (long i = 0; i <= n; i++) {
prime[i] = 1;
}
prime[0] = prime[1] = 0;
long upper_bound = std::sqrt(n);
for (long i = 2; i <= upper_bound; i++) {
if (prime[i] == 1) {
for (long j = 2; i * j <= n; j++)
prime[i * j] = 0;
}
}
long num_primes = 0;
for (long i = 0; i <= n; i++) {
if (prime[i] == 1) {
++num_primes;
// std::cout << i << std::endl;
}
}
return num_primes;
}
int main() {
std::cout << "Enter the sieve size: ";
std::string line;
std::getline(std::cin, line);
std::cout << std::endl;
long len = std::stol(line);
long num_primes = isprime(len);
std::cout << "There are " << num_primes << " primes <= " << len << std::endl;
return 0;
}

Getting bizarre issue with variables outside the main method?

I have some global variables defined just above my main method. When I try to call the function "fib()" while using those variables, I get incorrect results.
When I move the variables into the local scope of the function, I get correct results.
Why does this happen? Here is the correct code:
using namespace std;
#include <iostream>
#include <vector>
vector <int> fibVals;
int fibInput;
int fib(int n);
int main()
{
cout << "Please enter 3 Fibonacci numbers you wish to find:: \n";
for(int i = 0; i < 3; i++)
{
cin >> fibInput;
fibVals.push_back(fibInput);
}
cout << "The values at those Fibonacci numbers are(in order)::\n";
for(int i = 0; i < 3; i++)
{
cout << fib( fibVals[i] ) << "\n";
}
return 0;
}
int fib(int n)
{
int sum = 0;
int fib1 = 1;
int fib2 = 0;
if (n == 0 || n == 1)
return n;
for(int i = 2; i <= n; i++)
{
sum = fib1 + fib2;
fib2 = fib1;
fib1 = sum;
}
return sum;
}
The incorrect code has the three variables "sum", "fib1", and "fib2" above the main method. Why does this not work, but declaring the variables inside the function does?
Edit: below is the incorrect code. Note that the only difference is the placement of the variables.
using namespace std;
#include <iostream>
#include <vector>
vector <int> fibVals;
int fibInput;
int fib(int n);
int sum = 0;
int fib1 = 1;
int fib2 = 0;
int main()
{
cout << "Please enter 3 Fibonacci numbers you wish to find:: \n";
for(int i = 0; i < 3; i++)
{
cin >> fibInput;
fibVals.push_back(fibInput);
}
cout << "The values at those Fibonacci numbers are(in order)::\n";
for(int i = 0; i < 3; i++)
{
cout << fib( fibVals[i] ) << "\n";
}
return 0;
}
int fib(int n)
{
if (n == 0 || n == 1)
return n;
for(int i = 2; i <= n; i++)
{
sum = fib1 + fib2;
fib2 = fib1;
fib1 = sum;
}
return sum;
}
I understand the concept of scope. I thought that making those three variables global(outside main) would make no difference than if they were made local(inside fib() ).
You should try to make your question clearer. Nevertheless I will take a shot in the dark and try to respond to what I believe your question is. Think what happens if you move sum, fib1, and fib2 outside the function fib(), in other words you make them global. They will keep their value across function invocations (technically, they have static storage duration). Hence, when you invoke fib() the second time, sum will be equal to the previous value returned by fib(). However, when you put them inside the function, they are local to that scope, and at each function invocation they start "fresh" and are re-initialized (technically they have automatic storage duration).

How do i find the maximum number in an Array using a function

In my c++ class, i'm supposed to use this " int mymaximum(int a[], int numberOfElements); " function to find the maximum number in an Array. The function should return the largest in this array.
This is the code I have so far without the function I need to use. Thanks in advance and sorry about the messy code, still learning.
#include <iostream>
using namespace std;
int main() {
int Array[] = {23,2,90,53,38};
int mymaximum = 0;
for(int i = 0; i < 5; i++){
if(Array[i] > mymaximum){
mymaximum = Array[i];
}
}
cout << "The Max is: " << mymaximum << "\n";
return 0;
}
Just wrap around the logic to find maximum in a function. Like this:
int mymaximum(int a[], int numberOfElements)
{
// moved code from main() to here
int mymaximum = 0;
for(int i = 0; i < numberOfElements; i++)
{
if(a[i] > mymaximum)
{
mymaximum = a[i];
}
}
return mymaximum;
}
Aso, in order to support negative numbers, modify your logic like this:
int mymaximum(int a[], int numberOfElements)
{
// moved code from main() to here
int mymaximum = a[0];
for(int i = 1; i < numberOfElements; i++)
{
if(a[i] > mymaximum)
{
mymaximum = a[i];
}
}
return mymaximum;
}
Note that now I initialize maximum with the first entry in the array!
In main() call your method like this:
int main() {
int Array[] = {23,2,90,53,38};
cout << "The Max is: " << mymaximum(Array, sizeof(Array) / sizeof(Array[0])) << "\n";
return 0;
}
I'll show the overall structure without solving the homework for you:
#include <iostream>
using namespace std;
int mymaximum(int a[], int numberOfElements) {
int ret = 0;
// compute the maximum and store in `ret'
...
return ret;
}
int main() {
int Array[] = {23,2,90,53,38};
cout << "The Max is: " << mymaximum(Array, sizeof(Array) / sizeof(Array[0])) << "\n";
return 0;
}
In case you're wondering, sizeof(Array) / sizeof(Array[0]) computes the size of the array so that you don't have to hard-code it here.
Just move your logic into the desired function as follows:
int mymaximum(int Array[], int numberOfElements)
{
int mymaximum = 0;
for(int i = 0; i < numberOfelements; i++){
if(Array[i] > mymaximum){
mymaximum = Array[i];
}
}
return mymaximum;
}
Put that above int main(), then inside main() replace the removed code with:
int mymaximum = ::mymaximum(Array, 5);
(The :: wouldn't be needed if either the local variable or the function had different names).
You should then apply the suggestion in sasha's comment to use [0] as the initial guess at a maximum.
Replace your for loop structure with this:
int max(0);
max = mymaximum(Array, 5);
In the function mymaximum use this code:
int max(a[0]);
for(auto i(1); i < numberOfElements; ++i)
if(a[i] > max)
max = a[i];
return max;

Function to stall for time with <Windows.h> and continue to other functions

My waitSeconds() functions takes an integer for the number of seconds to wait. I am using the to use Sleep(msec)and converting to seconds at this point I want to try doing it like this and know it's not elegant. However my programs does not execute the rest of my functions calls and I am head banging.
Ultimately, what I want to use this functions call for is to call it with my slowTriangle() function and distressCall() that loops forever with a pause of what the parameter of waitSeconds has been passed through. I hope this last part is making sense. Anyways thank you for any guidance any of you experienced members can provide.
#include <iostream>
#include <Windows.h>
using namespace std;
int dots(int count);
int dashes(int count);
void sendSOS();
void waitSeconds(int seconds2Wait);
int triangle(int rows);
int slowTriangle();
void distressCall();
int main()
{
dots(3);
dashes(3);
sendSOS();
cout << "\n\n ";
waitSeconds(1);
int triangle(4);
int slowTriangle();
void distressCall();
return 0;
}
int dots(int count) // counts DOWN the number of dots that the int is set as a parameter
{
for (; count >= 1; count--)
{
cout << "." ;
}
return 0;
}
int dashes(int count) // counts UP the number of dots that the int is set as a parameter
{
int i;
for (; count >= 1; count--)
{
cout << "-";
}
return 0;
}
void sendSOS()
{
dots(3);
dashes(3);
dots(3);
}
void waitSeconds(int seconds2Wait) //Sleeps for time specified
{
Sleep(1000 * seconds2Wait); //converts miliseconds to seconds
seconds2Wait = 2;
}
int triangle(int rows) //Prints a dot triangle
{
int i, j;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
cout << ". ";
}
cout << "\n";
}
return 0;
}
int slowTriangle(int rows) //Prints a dot triangle with sleep paramter passed in
{
int i, j, seconds2Wait;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
waitSeconds(3);
{
cout << ". ";
}
cout << "\n";
}
return 0;
}
void distressCall()
{
sendSOS();
waitSeconds(2);
}
The correct C++ answer is already in the comments: std::this_thread::sleep_for
The WinAPI method (Sleep) is also possible.
The real reason why your "functions" appear to fail is because int triangle(4) defines a new variable in main, initialized to 4. This variable hides the global triangle function.
#include <ctime>
void pause (unsigned int seconds)
{
time_t goal = seconds + time(0);
while (goal > time(0));
}
#include <iostream>
#include <ctime>
using namespace std;
int dots(int count);
int dashes(int count);
void sendSOS();
void waitSeconds(int seconds2Wait);
int triangle(int rows);
int slowTriangle(int rows);
void distressCall();
int main()
{
dots(3);
dashes(3);
sendSOS();
cout << "\n\n";
waitSeconds(1);
triangle(4);
slowTriangle(4);
distressCall();
return 0;
}
int dots(int count) // counts DOWN the number of dots that the int is set as a parameter
{
for (; count >= 1; count--)
{
cout << "." ;
}
return 0;
}
int dashes(int count) // counts UP the number of dots that the int is set as a parameter
{
for (; count >= 1; count--)
{
cout << "-";
}
return 0;
}
void sendSOS()
{
dots(3);
dashes(3);
dots(3);
}
void waitSeconds(int seconds2Wait) //Sleeps for time specified
{
time_t goal = seconds2Wait + time(0);
while (goal > time(0));
}
int triangle(int rows) //Prints a dot triangle
{
int i, j;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
cout << ". ";
}
cout << "\n";
}
return 0;
}
int slowTriangle(int rows) //Prints a dot triangle with sleep paramter passed in
{
int i, j;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
waitSeconds(3);
cout << ". ";
}
cout << "\n";
}
return 0;
}
void distressCall()
{
sendSOS();
waitSeconds(2);
}
Implemented pause function as suggested and it works as intended now. Kudos to our other friend who wrote the ctime pause function. I also fixed some of your syntax errors :)
If you want distressCall() to run forever make it like this:
void distressCall()
{
while(true)
{
sendSOS();
waitSeconds(2);
}
}
Strongly recommend that you implement an escape mechanism though :).