Problems with recursive formula [duplicate] - c

This question already has answers here:
Division result is always zero [duplicate]
(4 answers)
Closed 3 years ago.
I'm trying to do a recursion for my coding class in C language. For some reason, the solution that I get is wrong, event though I made sure multiple times that the formula is correct.
This is what I am supposed to replicate in code.
double recursion(int n, int k, int flag, int subN, int rep)
{
if(rep == 0)
return 0;
if(flag == 0)
return sqrt(n/subN+recursion(n, ++k, ++flag, subN-2, --rep));
else
return sqrt(k/subN+recursion(--n, k, --flag, subN-2, --rep));
}
int main()
{
int n;
scanf("%d", &n);
printf("%f", recursion(n, 0, 0, 2*n, n));
return 0;
}
For n = 6, I get 1.021897, for n = 7, I get 1.005430
My solution:
n - the number we are starting from, user inputs this number in
console
k - this integer is supposed to be that counter from 1
subN - this is the number we are dividing n with
rep - acts as a counter to know when the recursion should stop (it always ends after n cycles)

When dividing two int you get integer division, where the answer is an integer. Replace at least one of the operands with a double to get floating-point calculations.
double recursion(int n, int k, int flag, int subN, int rep)
{
if(rep == 0)
return 0;
if(flag == 0)
return sqrt((double)n/subN+recursion(n, k+1, flag+1, subN-2, rep-1));
else
return sqrt((double)k/subN+recursion(n-1, k, flag-1, subN-2, rep-1));
}
or even better just change the function signature to
double recursion(double n, double k, int flag, double subN, int rep)

Related

Given a number N and a sorted array A, check if there are two numbers in A whose product is N

Given a number N and a sorted array A, design an algorithm - using the Divide and Conquer approach - to check if there exist index i and index j such that A[i]*A[j] == N (return 1 if present, 0 if not).
I'm having a hard time proceeding in the required (recursive) way. I think I figured out only a part of one possible solution, but even there I'm not a 100% sure if it's correct: I thought that if the product between the first element and the central element of the array is greater than N, then the numbers I'm looking for (if present) are certainly in the first half of the array, so I can recursively call the function on that part, like so (I'm using C):
int productN(int A[], int i, int j, int N){
// missing base case
int m = (i+j)/2;
if(A[i]*A[m] > N){
return productN(A, i, m, N);
} else{
// do something else
}
}
int main(){
int A[]={1, 2, 3, 4, 5};
printf("%d\n", productN(A, 0, 4, 15)); // initial value for i and j are the first and last index of the array
return 0;
}
Apart from that, I'm stuck, I can't even think of a base case, so any help will be greatly appreciated, thanks.
Edit:
Based on your very helpful answers, using binary search, I think I got it:
int productN(int A[], int i, int j, int N){
int m = (i+j)/2; // central element of the current array
int x;
for(x=i; x<=m; x++){
if(N%A[x]==0 && binarySearch(A, m, j, N/A[x]))
return 1;
}
if(i!=j){
if(productN(A, i, m, N) || productN(A, m+1, j, N))
return 1;
}
return 0;
}
Is it good? Can it be better?
Edit: it's been a while now since I asked this question, but I wrote another solution, simplier to read. I'll leave it here in case anyone is interested.
int productN(int A[], int i, int j, int N, int size){
if(i==j){ // base case
if(N%A[i]==0)
return binarySearch(A, 0, size-1, N/A[i]);
else
return 0;
}
int m = (i+j)/2;
if((N%A[m])==0){
if(binarySearch(A, 0, size-1, N/A[i]))
return 1;
}
return productN(A, i, m, N, size) || productN(A, m+1, j, N, size);
}
Using Divide and Conquer, you can use an approach similar to merge sort algorithm. As the comments suggest, there are easier approaches. But if Divide and Conquer is a must, this should suffice.
(I'm not proficient in C, so I'll just write the algorithm)
def productN(arr):
x = len(arr)
left_half = arr[0:x/2]
right_half = arr[x/2:]
if productN(left_half) or productN(right_half):
return True
for i in left_half:
if N%i==0 and binary_search(right_half, N/i):
return True
return False

Weird compilation issues

#include <stdlib.h>
#include <math.h>
#include <stdio.h>
int rev (int N);
int rev(int N){
return ((N <= 9)) ? N : rev(N / 10) + ((N % 10) * (pow(10, (floor(log10(abs(N))))))) ;
}
int main(void){
int r, n;
scanf("%d", &n);
r = rev(n);
printf("%d %d", r, n);
return EXIT_SUCCESS;
}
A simple code just to find out the reverse of a number. Everything is fine. Until I put a number with more than 2 digits. Things behave weirdly, somehow the last digit is always 0 of the reversed number. I have checked out in online compilers where things behave just fine. However the problem arises when I run the code on my own machine. I am on Windows 10 with MINGw. Could you guys suggest me a solution. I previously had problems where the value stored in an int matrix changes to huge values which is practically impossible to store in int due to it's size.
Using the pow and floor function, working with floats will not always round the way you'd expect.
As already commented, work with integers.
Propose doing this digit-by-digit, and sticking with integers. A proposal for your rev() function:
int rev(unsigned int N)
{
unsigned int res = 0;
while(N>0)
{
// pick off lowest digit
unsigned int digit = N%10;
// put into result, moving up all previous digits by doing *10
res = 10*res+digit;
// remove this digit from input value
N/=10;
}
return res;
}

Even though I use % 1000000007 it still results on 0 [duplicate]

This question already has answers here:
Need help in mod 1000000007 questions
(4 answers)
Closed 4 years ago.
my goal on this code is to make exponential operations without pow().
It works for evey value a^b which b <= 30. I'm aware that I should be using x % 1000000007 to prevent integers overflows.
#include <stdio.h>
int main(void) {
int i, a, b, rst;
rst = 1;
scanf("%d %d", &a, &b);
for (i = 0; i < b; i++){
rst = rst * a;
if( b == 0){
rst = 1;
}
}
printf("%d\n", rst % 1000000007);
return 0;
}
Why does it returns a "0" for example on "2^40 % 1000000007" even though I'm using % 1000000007?
First, you don't need if statement in for loop.
Second, you are trying to stop integer overflow after it already happens. So you need to do it after every multiplication operation.
Third, you can use unsigned long long int instead of int, because int is machine dependent (may be 1000000007 is too big for int on your machine).
I guess this should work:
#include <stdio.h>
int main()
{
unsigned long long int i, a, b, rst;
scanf("%llu %llu", &a, &b);
rst = 1;
for (i = 0; i < b; i++){
rst = (rst * a) % 1000000007;
}
printf("%llu\n", rst);
return 0;
}

Finding frequency of an integer in an array and calculating x to the nth power

I am trying to solve two different C problems and would like some help and advice in order to better understand how C works and if I'm on the right track with these.
First problem is: To write a function that counts the number of times the value (x) appears among the first (n) elements of an array and returns that count as the frequency of x in theArray. So, an example would be if the array being passed contained the values {5, 7, 23, 8, 23, 67, 23}. And n was 7 and x was 23, then it would return a value of 3 since 23 occurs 3 times within the first 7 elements of the array.
Here is what I have so far:
#include <stdio.h>
#define SIZE 20 /* just for example - function should work with array of any size */
int frequency (int theArray[], int n, int x)
{
int i;
int count = 0;
for (i = 0; i < n; i++)
{
if (theArray[i] == x)
{
count = count++;
}
}
return (count);
}
int main(void)
{
/* hard code n and x just as examples */
int n = 12; /* look through first 12 items of array */
int x = 5; /* value to find */
int numberFrequency;
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
numberFrequency = frequency (theArray[SIZE], n, x);
printf ("%i", numberFrequency);
return 0;
}
Currently I'm getting a run time error message and believe it has something to do with the for loop function.
Second problem is: Write a function that raises an integer to a positive integer power. Have the function return a long int, which represents the results of calculating x to the nth power. Do not use the C pow library function and do not use recursion!
My code so far:
#include <stdio.h>
int x_to_the_n (int x, int n)
{
int i;
long int result = 1;
if (n == 0)
{
return(result);
}
else
{
for (i = 0; i < n ; ++i)
{
/* equation here - How can I make (x*x*x*x*x*x,etc...? */
result = x*(n*x);
}
}
return (result);
}
int main(void)
{
int x =4;
int n =5;
long int result;
result = x_to_the_n (x, n);
printf ("%i", result);
return 0;
}
I can't use recursion so that is out of the question. So, I thought the next best thing would be a for loop. But I'm a little stuck in how I would go about making a for loop do (xxx*x....) based on value of (n). Any help and advice would be appreciated!
In the first problem you give an element after the array as a parameter to your function.
You define a long int array, and pass it into a function expecting an int array.
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
should be
int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
Instead of this:
numberFrequency = frequency (theArray[SIZE], n, x);
try this:
numberFrequency = frequency (theArray, n, x);
And replace:
count = count++;
with:
count++;

Detecting Overflow In nCr Function

I have two functions here that together compute the nCr:
int factorial(int n) {
int c;
int result = 1;
for (c = 1; c <= n; c++)
{
result = result*c;
}
return result;
}
int nCr(int n, int r) {
int result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
I am having trouble with an error check I need to implement. As n gets larger, I won't have the ability to computer n! and this error check has to exist in both nCr and factorial. They both must detect this overflow.
Currently, when I enter a number that is too large for computation, I get a floating type error returned from the command line.
I am having trouble accounting for this overflow check. Any help would be much appreciated, thanks.
A better way of calculating binomial coefficients
typedef unsigned long long ull;
ull nCr(int n, int r) {
ull res = 1;
if (r > n - r) r = n - r;
for (int i = 0; i < r; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
In your code, the maximum value is always factorial(n),
so you only need to check that n! isn't bigger than 2.147.483.647 (max int value).
Please note that the stored max value can be different based on the size of the int type in memory (different machines can specify different sizes).
However, the last bit in int type variables is reserved for storing the sign (+ or -), thus the max value can be half of 65.535 and 4.294.967.295 i.e. 32.767 and 2.147.483.647 for int types.
SIZE_OF_INT(bits) MAX VALUE(UNSIGNED) MAX_VALUE(SIGNED)
---------------------------------------------------------------
16 65.535 32.767
32 4.294.967.295 2.147.483.647
The value of 13! can go beyond the max value of the int type (in 32 bit).
12! = 479.001.600 and
13! = 6.227.020.800
So, you need to check in nCr(int n, int r) that the max value of n is always less than 13 (i.e. n<=12) and r<=n.
And in factorial(int n): n<=12.

Resources