Nearest value in an array - c++

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

Related

What return type should I use for my function to print Fibonacci numbers?

I'm trying to write a function that prints all Fibonacci numbers between the range of x and y. I almost have it but I have no idea what return type to use for the function genFib(int min, int max){ I thought bool was right but when I tested the code, the line cout << genFib(5, 20) << endl;prints 5 8 13 0 adding the zero at the end. What return type should I use to avoid having a zero print at the end? This is all of my current code.
#include <iostream>
#include <cmath>
using namespace std;
bool perfectSquare(int x){
int s = sqrt(x);
return (s*s == x);
}
bool isFibonacci(int n){
return perfectSquare(5*n*n + 4) ||
perfectSquare(5*n*n - 4);
}
bool genFib(int min, int max){
int newMax = 0, newMin = 0;
if(min > max){
newMax = min;
newMin = max;
}else{
newMax = max;
newMin = min;
}
cout << "Fib numbers: ";
for(int i = newMin; i <= newMax; i++)
if(isFibonacci(i)) cout << i << " ";
return false;
}
int main(){
cout << genFib(5, 20) << endl;
return 0;
}
The last 0 you are seeing is there because you are returning false from genFib(), and then printing it. Because you are printing everything inside your genFib() method, you don't need to print the result from the method, or return anything from it. If you try the following, you won't print the result of genFib(), which is your trailing 0.
int main(){
int x = 372; // Simply a random number
genFib(5, 20);
return 0;
}
Since you also don't care about the return value of genFib(), you should return void instead of false. That would prevent anything from being printed if you do print the result of the method.

what does int numbers[n+2]; statement do?

#include<iostream>
int fastFibonacci(int n)
{
int numbers[n+2]; // int numbers[n].
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
}
return numbers[n];
}
int main() {
int n;
std::cout << "Enter a Number";
std::cin >> n;
int result = fastFibonacci(n);
std::cout << result << "\n";
return 0;
}
in this code when i enter input 0 or 1 get correct answer. But the problem is that when i replace int numbers[n+2]; with the commented part it start giving me wrong answer when input is 0 or 1. why? anyone please explain me.
In this function
int fastFibonacci(int n)
{
int numbers[n+2]; // int numbers[n].
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
}
return numbers[n];
}
there is used a variable length array with n + 2 elements declared in this line
int numbers[n+2]; // int numbers[n].
Variable length arrays is not a standard C++ feature. It can be implemented as own language extension of a C++ compiler.
Using the variable length array makes the function very unsafe because there can occur a stack overflow.
As within the function there is explicitly used two elements of the array
numbers[0] = 0;
numbers[1] = 1;
then the array shall have at least two elements even when the parameter has a value less than 2.
To calculate the n-th Fibonacci number there is no need to declare an array of such a size.
Apart from this the function argument shall have an unsigned integer type. Otherwise the function can invoke undefined behavior if the user passes a negative number.
Also for big values of n there can be an integer overflow for the type int.
The function can be implemented in various ways.
Here is one of possible its implementations.
#include <iostream>
#include <functional>
unsigned long long fibonacci( unsigned int n )
{
unsigned long long a[] = { 0, 1 };
while ( n-- )
{
a[1] += std::exchange( a[0], a[1] );
}
return a[0];
}
int main()
{
const unsigned int N = 10;
for ( unsigned int i = 0; i < N; i++ )
{
std::cout << i << ": " << fibonacci( i ) << '\n';
}
return 0;
}
The program output is
0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
int numbers[n+2]; is the declaration of an array of ints with space for n + 2 ints, this is a variable lenght array and is not part of C++ standard, though some compilers allow it it's not somenthing you should use.
If you need a variable lenght array use std::vector.
With int numbers[n+2]; if n is equal to 0 you still have space for 2 ints, if you have int numbers[n]; the array will have space for 0 ints, so the code will fail because you are trying to access memory that does not exist with numbers[0] and numbers[1].
There are several good ways to implement the Fibonacci sequence, in the site you can find many questions regarding this matter in several programming languages, here is one of them Fibonacci series in C++
Edit
So I've seen your comments about using a vector, for making the sequence you wouldn't need the vector just two variables to store the two numbers to add, to store the sequence in a vactor, you can do somenthing like:
#include <iostream>
#include <vector>
#include <iomanip>
//passing the vector by reference
void fastFibonacci(unsigned long long n, std::vector<unsigned long long>& sequence) {
unsigned long long first = 0;
unsigned long long second = 1;
sequence.push_back(first); //add first values to the vector
sequence.push_back(second); //add first values to the vector
for (unsigned long long i = 0, value = 0; i < n && value <= LLONG_MAX ; ++i) {
value = first + second;
first = second;
second = value;
sequence.push_back(value); //adding values to the vector
}
}
int main() {
unsigned long long limit; //number of values in the sequence
int num = 1;
std::vector<unsigned long long> sequence; //container for the sequence
std::cout << "Enter upper limit: ";
std::cin >> limit;
fastFibonacci(limit, sequence);
//print the sequence in a range based loop formatted with <iomanip> library
for(auto& i : sequence){
std::cout << std::setw(4) << std::left << num++ << " " << i << std::endl;
}
return 0;
}
If you want to print just one of the numbers in the sequence, just use, for instance:
std::cout << sequence[10];
Instead of the whole vector.
The code you post in the comment to the other answer won't work because the access to the vector is out of bounds in numbers[i] = numbers[i - 1] + numbers[i - 2];, if for instance i = 5, your vector only has 2 nodes but you are accessing the 6th node numbers[5].

Program not loading array correctly

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++;

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++ 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.