Program not loading array correctly - c++

Question at hand: Write a function primeTableInRange to generate a table to show whether each number in the range from startNum up to endNum is a prime number. When the number is not a prime number, we will only show a ‘*’. When the number is a prime number, we will show the number.
My code:
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int primetableinarray(int userarray[], int arraysize);
int main()
{
int startNum, endNum;
cout<< "Enter your first number in the range" << endl;
cin>>startNum;
cout<< "Enter your last number in the range" << endl;
cin>>endNum;
int arraysize = endNum - startNum;
int userarray[arraysize];
for (int i=startNum;i<=endNum;i++)
userarray[i]= startNum++;
primetableinarray(userarray, arraysize);
return 0;
}
int primetableinarray(int userarray[], int arraysize)
{
for (int i=2;i<arraysize;i++)
{
bool prime=true;
for (int r=2;r*r<i;r++)
{
if (i % r ==0)
{
prime=false;
break;
}
}
if(prime) cout << i << endl;
else
if(true) cout<< "*" << endl;
}
}
Issue is it doesn't start at "startNum" and doesn't end at "endNum". It actually goes from 0 to arraysize. Also it calculates 4 as a prime number. What am I missing here?

Be careful! Arrays always start at 0 and end at arraysize in your case. You cannot have arbitrary indexing. You could do the following:
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
for (int i=0;i<arraysize;i++)
userarray[i]= startNum+i;
Also, since we start at 0 you need to add +1 in ´arraysize´ to include ´endNum´ in your ´userarray´

try to change this
from:
for (int r=2;r*r<i;r++)
to
for (int r=2;r<i;r++)

At nowhere in your printing function do you even recognize your array. You simply begin looping numbers up to your array size. If you took the array out of your function arguments it would still work, so why are you including it? Your for loops just disregard any values in your array and begin looping from 2 arbitrarily.
As for why 4 is calculated as a prime number, it is because when your second loop starts it sees that 2*2=4 and therefore not less than 4, which is the number you are testing. This results in it skipping over the loop and never setting prime to false. Make the condition in the second for loop to <= or else any perfect square with no other factors will be labelled as prime, such as 25.
Also on a side note, how did this ever compile? You use a dynaimc variable to initiate an array size. That doesn't work and when I tried to run your code to see the output I got errors. Try using std::vector<int>. When you use the for loop to fill the vector you use the values as indexes which is completely and utterly wrong. This is when you should loop from zero to your arraysize because that it the address within the array. You also include unecessary headers like ctime and cmath, and have if(true) in your code for no reason.

#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int primetableinarray(int userarray[], int arraysize);
int main()
{
int startNum, endNum;
cout<< "Enter your first number in the range" << endl;
cin>>startNum;
cout<< "Enter your last number in the range" << endl;
cin>>endNum;
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
for (int i=startNum;i<endNum;i++)
userarray[i]= startNum++;
primetableinarray(userarray, arraysize);
return 0;
}
int primetableinarray(int userarray[], int arraysize)
{
for (int i=2;i<=arraysize;i++)
{
bool prime=true;
for (int r=2;r<i;r++)
{
if (i % r ==0)
{
prime=false;
break;
}
}
if(prime) cout << i << endl;
else
if(true) cout<< "*" << endl;
}
}

The declaration for the array (int userarray[arraysize];) is illegal, the array bounds need to be known at compile time. This should not even compile, or it produces a zero-size array.
Afterwards, you randomly access unallocated memory, whcih is UB

Change
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
To
int userarray[1];
int arraysize = endNum - startNum;
userarray[arraysize];
Also, add a return value to the primetableinarray function.

Here is the correct program .
#include <iostream>
using namespace std;
void primetableinarray(int low, int high) ;
int main()
{
int low, high, i, flag;
cout<< "Enter low numbers ";
cin>> low;
cout<< "Enter high numbers ";
cin>>high;
cout<< "Prime numbers between " << low << "and are: " << high <<endl;;
primetableinarray(low, high);
return 0;
}
void primetableinarray(int low, int high) {
int i, flag;
while (low <= high)
{
flag = 0;
for(i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout<< low <<endl;
else
cout<< "*" <<endl;
++low;
}
}
Output :
Enter low numbers 1
Enter high numbers 10
Prime numbers between 1and are: 10
1
2
3
*
5
*
7
*
*
*
There are copule of problem in your code :
int arraysize = endNum - startNum;
int userarray[arraysize];
How does it compile , it will be compilation error. you can allocate memory dynamically and use it .
for (int i=startNum;i<=endNum;i++)
userarray[i]= startNum++;
this is wrong i = startNum and arraysize = arraysize +1 if you are comparing " i<=endNum " .
Correct way is :
for (int i=0;i<=endNum;i++)
userarray[i]= startNum++;

Related

Sum of factoriais to be equal a given number

I'm trying to solve the following problem:
What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)
Example:
Input: 10, Output: 3. (10 = 3! + 2! + 2!)
Input: 25, Output: 2. (25 = 4! + 1!)
My code:
#include<bits/stdc++.h>
using namespace std;
int a;
int rec(int vet){
int count = 0;
a = a - vet;
if(a >= vet){
count++;
rec(vet);
}
count++;
return count;
}
int main(){
int vet[8] = {1}, count = 0;
cin >> a;
for(int i = 2; i <= 8; i++){
vet[i-1] = vet[i-2]*i;
}
for(int i = 7; i >= 0; i--){
if(a < vet[i]){
continue;
}
count += rec(vet[i]);
}
cout << count << endl;
}
My logic:
1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;
2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.
This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.
Can you find where am I wrong? Or if my solution is not good and I should try another approach.
Thanks for the help!
The problem is easily solved by a recursive approach.
Here is checked code:
#include <iostream>
using namespace std;
int factorial(int n) {
return n<=1 ? 1 : n * factorial(n-1);
}
int MinFact(int number)
{
static int num_of_facts;
int a = 1;
if (number)
{
while(factorial(a+1)<=number)a++;
cout << a << "!" << endl;
num_of_facts++;
MinFact((number-factorial(a)));
}
return num_of_facts;
}
int main()
{
int num;
cout << "Enter number" << endl;
cin >> num;
num = MinFact(num);
cout << "Number of factorials: " << num;
return 0;
}
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.
A simple solution would be to replace the rec function as follows
int rec(int vec) {
int count = a / vec;
a = a % vec;
return count;
}
Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.

C++: find first prime number larger than a given integer

Question: How to find, for a given integer n, the first prime number that is larger than n?
My own work so far
I've managed to write a program that checks whether or not a given integer is a prime or not:
#include <iostream>
#include <cmath>
using namespace std;
bool is_prime (int n)
{
int i;
double square_root_n = sqrt(n) ;
for (i = 2; i <= square_root_n ; i++)
{
if (n % i == 0){
return false;
break;
}
}
return true;
}
int main(int argc, char** argv)
{
int i;
while (true)
{
cout << "Input the number and press ENTER: \n";
cout << "To exit input 0 and press ENTER: \n";
cin >> i;
if (i == 0)
{
break;
}
if (is_prime(i))
cout << i << " is prime" << endl;
else
cout << i << " isn't prime'" << endl;
}
return 0;
}
I'm struggling, however, on how to proceed on from this point.
You have a function is_prime(n), and a number n, and you want to return the smallest number q such that is_prime(q)==true and n <= q:
int q = n;
while (!is_prime(q)) {
q++;
}
// here you can be sure that
// 1. q is prime
// 2. q >= n -- unless there was an overflow
If you want to be a bit more efficient, you can check explicitly for the even case, and the increment by 2 each time.
It's a concrete example of a general theme: if you have a test function and a method for generating elements, you can generate the elements that pass the test:
x = initial_value
while (something) {
if (test(x)) {
// found!
// If you only want the first such x, you can break
break;
}
x = generate(x)
}
(note that this is not a valid C++ code, it's pseudocode)
int i;
**int k_koren_od_n = (int)(sqrt(n) + 0.5)**
for (i = 2; i <= k_koren_od_n ; i++){
To get around casting issues, you might want to add this fix.

Whats wrong in my code! I want to print Fibonacci Series with values less than 4000000

I think I there is some problem in implementation of my loop!
Here's my code.
#include <iostream>
using namespace std;
int main()
{
int i=2;
long long int FiboNo[100];
FiboNo[0] = 1;
FiboNo[1] = 2;
do{
FiboNo[i]=FiboNo[(i-1)]+FiboNo[(i-2)];
cout<<FiboNo[i]<<endl;
i++;
}while(FiboNo[i]<4000000);
return 0;
}
do {
FiboNo[i] = FiboNo[(i - 1)] + FiboNo[(i - 2)];
cout << FiboNo[i] << endl;
i++;
} while (FiboNo[i] < 4000000);
You are incrementing i before you compare.
do {
FiboNo[i] = FiboNo[(i - 1)] + FiboNo[(i - 2)];
cout << FiboNo[i] << endl;
} while (FiboNo[i++] < 4000000);
is what you want to do.
Here's what's happening:
i 2
fibo[2] is 2
now i is 3
fibo[3] is 0
This has no problem, when fibo[someIndex] reaches the limit. It wont come out, because your value is always a 0.

C++ factorial of 0

I am writing a program to find the factorial of a user inputted number. My program works from, except for finding the factorial of 0. The requirement is that the factorial of 0 should output one, but I cannot think of a way to write this capability into the code without creating a special case for when 0 is entered. This is what I have so far
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int startingNumber = 0;
double factorialize = NULL;
while(startingNumber != -1) {
cout << "Enter the numbr to factorial: ";
cin >> startingNumber;
factorialize = startingNumber;
for(int x=startingNumber-1;x>=1;x--) {
factorialize = factorialize*x;
}
cout << factorialize << endl;
factorialize = NULL;
}
return 0;
}
This outputs a factorial accurately for all cases except 0. Is there a way to do this that doesn't require a special case? I am thinking no because when I read about the reasons for why 0! is 1, it says that it is defined that way, in other words, you cannot reason your way into why it is 1. Just like x^0, 0! = 1 has a different logic as to why than why 2^2 is 4 or 2! = 2.
try this:
factorialize = 1;
for(int x=2; x<=startingNumber;x++)
factorialize *= x;
Try this:
for (unsigned int n; std::cin >> n; )
{
unsigned int result = 1;
for (unsigned int i = 1; i <= n; ++i) { result *= i; }
std::cout << n << "! = " << result << "\n";
}
You can change the result type a bit (unsigned long long int or double or long double), but ultimately you won't be able to compute a large number of factorials in hardware.
First of all I do not see how it can be calculated accurately, as you multiply startingNumber twice. So just fix the logic with:
factorialize = 1.0;
for(int x=startingNumber;x>=1;x--) {
factorialize = factorialize*x;
}
And it should calculate factorial properly as well as handling 0 the proper way.
Also you should not use NULL as initial value for double, it is for pointers.
There is a complete factorial of number program of C++ which includes the facility of factorial of positive number,negative and zero.
#include<iostream>
using namespace std;
int main()
{
int number,factorial=1;
cout<<"Enter Number to find its Factorial: ";
cin>>number;
if(number<0
)
{
cout<<"Not Defined.";
}
else if (number==0)
{
cout<<"The Facorial of 0 is 1.";
}
else
{
for(int i=1;i<=number;i++)
{
factorial=factorial*i;
}
cout<<"The Facorial of "<<number<<" is "<<factorial<<endl;
}
return 0;
}
You can read full program logic on http://www.cppbeginner.com/numbers/how-to-find-factorial-of-number-in-cpp/
The function listed below returns the factorial FASTER than any solution posted here to this date:
const unsigned int factorial(const unsigned int n)
{
unsigned int const f[13] = { 1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600 };
return f[n];
}
I looks silly but it works for all factorials that fit into a 32-bit unsigned integer.

Nearest value in an array

I am supposed write a function that is passed two parameters: a one-dimensional array of int values, and an integer value. The function finds the value in the array that is closest in value to the second parameter. My code works but not when I enter numbers 1-5 my output is 0. When I enter numbers above 5 then I start getting accurate results. I am not too sure why this is happening but here is my code so far:
#include <iostream>
#include <cmath>
using namespace std;
const int MAX = 5;
int searchNearest(int anArray[],int key)
{
int value = abs(key - anArray[0]);
int num = 0;
for(int x = 0;x < MAX; x++)
{
if(value > abs(key - anArray[x]))
{
value = abs(key - anArray[x]);
num = anArray[x];
}
}
return num;
}
int main()
{
int A[MAX] = {3,7,12,8,10};
int search;
int nearest;
cout << "Enter a number to search: ";
cin >> search;
nearest = searchNearest(A,search);
cout << "The nearest number is: " << nearest << endl;
system("pause");
return 0;
}
In your original code, numbers 1-5 are closest to the first element of the array. Because of this, the code in the if statement is never executed, and when you return num, you return its initial value, which happens to be 0. To fix this, just initialize num differently:
int num = anArray[0]; // <-- used to be 0