while running this code I am getting floating point exception pls explain why it is coming so.
#include <stdio.h>
int gcd(long int, int);
int main() {
int t, n, a, i;
long int abc;
scanf("%d", &t);
while (t--) {
abc = 1;
scanf("%d", &n);
abc = n * (n - 1);
for (i = n - 2; i > 1; i--) {
a = gcd(abc, i);
abc = ((abc * i) / a);
}
printf("%ld \n", abc);
}
return 0;
}
int gcd(long int a, int b) {
if (b == 0)
return a;
else {
return (b, a % b);
}
}
The else part in gcd function is bogus. You probably wanted to call gcd recursively and instead you are returning a % b. And as a result if a % b == 0 you divide by 0 on line 13.
The expression (b, a % b) is evaluated as two subexpressions separated by comma operator. The value of b is forgotten and the value of the whole expression becomes a % b.
The correct version:
int gcd(long int a, int b) {
if (b == 0)
return a;
else {
return gcd(b, a % b);
}
}
You should change a few things:
1) if(a == 0) instead of b==0 and return variable b
2) Use recursion gcd(b%a, a)
if (a == 0)
return b;
else {
return gcd(b%a, a);
}
And you can also use this short version
return a ? gcd(b%a,a) : b;
Proof:
We have m = n * (m div n) + m Mod n.
This equation is correct even if n = 1, because m div 1 = m and m mod 1 =0.
If n and m mod n it's multiple of d, also m is multiple of d, because n * (m div n) and m mod n / d.
On the other hand if m and n is multiple of e, to because m mod n = m -n * (m div n) is also multiple of e.
Related
I have a difficulty in implementing the tail recursive solution of the following problem:
There is another recursive relation for the double factorial, which also depends on the factorial, which is the above: (for n<20)
I have to implement a recursive relation of this equation- which I did as the above code that works:
long long factorial(int n) {
if (n < 0)
return 0;
if (n < 1)
return 1;
return n * factorial(n - 1);
}
long long doublefactorial(int n) {
if (n < 0)
return 0;
if (n < 2)
return 1;
return factorial(n) / doublefactorial(n - 1);
}
Now I have to implement the same problem using a tail recursion. can someone show me how to do this because I cant figure it out. (no need to implement the factorial function also in a tail recursive way)
test cases:
5!! = 15
10!! = 3840
18!! = 185,794,560
-10!! = 0
Here is a tail-recursive version of Factorial function:
long factorial(int n, int factor)
{
if (n == 0)
return factor;
return factorial(n-1, factor * n);
}
factorial(5, 1); // 120
Here's a tail-recursive double factorial with a simpler logic:
long doublefactorial(int n, int factor)
{
if (n < 0)
return 0;
if (n < 2)
return factor;
return doublefactorial(n-2, factor * n);
}
printf("%d ", doublefactorial(5,1)); // 15
printf("%d ", doublefactorial(10,1)); // 3840
printf("%d ", doublefactorial(18,1)); // 185794560
If you expand your math a little bit you'll get that the factorial function result is iterating between the numerator and the denominator of the final result.
so this code will do that in Python
def _factorial(n, m):
if n < 0:
return 0
elif n == 0:
return 1.0 * m
return _factorial(n - 1, n * m)
def factorial(n):
return _factorial(n, 1)
def _doublefactorial(n, m, is_even):
if n < 0:
return 0
elif n < 2:
return 1.0 * m
if is_even:
m *= factorial(n)
else:
m /= factorial(n)
return _doublefactorial(n - 1, m, (not is_even))
def doublefactorial(n):
return _doublefactorial(n, 1, True)
And in C:
unsigned int _factorial(const unsigned int n, const unsigned int m) {
if (n < 0) {
return 0;
} else if (n == 0) {
return m;
}
return _factorial(n - 1, n * m);
}
unsigned int factorial(const unsigned int n) {
return _factorial(n, 1);
}
double _doublefactorial(const unsigned int n, const double m, const char is_even) {
double value = m;
if (n < 0) {
return 0;
} else if (n < 2) {
return m;
}
if (is_even) {
value *= factorial(n);
} else {
value /= factorial(n);
}
return _doublefactorial(n - 1, value, !is_even);
}
double doublefactorial(const unsigned int n) {
return _doublefactorial(n, 1, 1);
}
Your definition of this double factorial function is incomplete: you need an initial value such as 0!! = 1. From the recurrence definition, it appears that p!! is the product of all numbers from 1 to p that have the same parity as p:
5!! = 1 * 3 * 5 = 15
6!! = 2 * 4 * 6 = 48
10!! = 2 * 4 * 6 * 8 * 10 = 3840
Computing the double factorial by computing the factorial and dividing by the result of the double factorial of the previous number will fail for numbers larger than 19 because of the limited range of integer types and the exponential growth of the factorial function. The double factorial grows quickly too, but its logarithm grows half as fast as that of the factorial function.
Here is an recursive function:
unsigned long long doublefactorial(int n) {
if (n < 0)
return 0;
if (n < 2)
return 1;
return n * doublefactorial(n - 2);
}
Here is a tail recursive implementation with a helper function:
unsigned long long doublefactorial_helper(int n, unsigned long long res) {
if (n < 2)
return res;
return doublefactorial(n - 2, res * n);
}
unsigned long long doublefactorial(int n) {
return doublefactorial_helper(n, n >= 0);
}
The trick to convert the first function to a tail recursive one is instead of waiting for the result and multiplying then by n, pass an updated intermediary result to the recursive function. The multiplications are performed in the opposite order but will produce the same result (even modulo ULLONG_MAX+1).
What is the problem with this code?
#include <stdio.h>
#include <stdlib.h>
#include "time.h"
void createNumb(int RandomNumber) {
srand(time(NULL));
int a, b, c, d;
a = rand() % 10 + 0;
b = rand() % 10 + 0;
c = rand() % 10 + 0;
d = rand() % 10 + 0;
while (b == a) {
b = rand() % 10 + 0;
}
while (c == b || c == a) {
c = rand() % 10 + 0;
}
while (d == c || d == b || d == a) {
d = rand() % 10 + 0;
}
RandomNumber = ("%d%d%d%d", a * 1000 + b * 100 + c * 10 + d * 1);
}
int main() {
int x;
createNumb(x);
printf("%d", x);
}
When I run this program, it always give me the result 0.
I want it to print a random 4-digit number (each digit must be unique). What is the problem?
Your createNumb function returns void instead of an int.
You should use srand() only once, so it’s better move it to your main.
Your createNumb function should return a random integer, like this:
int createNumb(void) {
/*
** Simplified for readability.
** Here you would use your function that generates 4 different digits
*/
return rand();
}
int main(void) {
srand(time(NULL))(
int x = createNumb();
printf("%d" , x);
}
Or, if you want createNumb to fill an existing integer, use a pointer:
void createNumb(int *randomNumber) {
/*
** Simplified for readability.
** Here you would use your function that generates 4 different digits
*/
*randomNumber = rand();
}
int main(void) {
int x;
srand(time(NULL))
createNumb(&x); // Passing a pointer to x
printf("%d" , x);
}
There are some problems in your C code, coming from a different language:
use return to return a value from a function and specify the return type before the function name`.
our attempt at formating the number is incorrect and unneeded. Incidentally, RandomNumber = ("%d%d%d%d", a * 1000 + b * 100 + c * 10 + d * 1); uses the operator , that ignores its left operand and evaluates to the right operand, whose value is stored into a local variable with automatic storage duration, and is lost upon function exit. Just use return a * 1000 + b * 100 + c * 10 + d * 1;.
to compute a 4 digit pseudo-random value, you could just use rand() % 10000, but an approach such as your may be needed for more digits or for specific constraints such as unique digits.
to make your results more random, use a faster changing source for srand() such as clock() and initialize the pseudo-random number generator just once int the main() function.
you could use the printf format "%04d" to make display an initial 0 if the result is less than 1000.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int createNumb(void) {
int a, b, c, d;
a = rand() % 10;
b = rand() % 10;
c = rand() % 10;
d = rand() % 10;
while (b == a) {
b = rand() % 10;
}
while (c == b || c == a) {
c = rand() % 10;
}
while (d == c || d == b || d == a) {
d = rand() % 10;
}
return a * 1000 + b * 100 + c * 10 + d;
}
int main() {
int x;
srand(clock());
x = createNumb();
printf("%04d\n", x);
return 0;
}
Note that you can avoid the loops in creatNumb(). Here is a modified version that takes an argument from the command line to produce multiple results.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int createNumb(void) {
int a, b, c, d, bb, cc, dd;
a = rand() % 10;
b = rand() % 9;
c = rand() % 8;
d = rand() % 7;
bb = (b >= a);
cc = (c >= a) + (c >= b);
cd = (d >= a) + (d >= b) + (d >= c);
return a * 1000 + (b + bb) * 100 + (c + cc) * 10 + (d + dd);
}
int main(int argc, char *argv[]) {
int x, n;
srand(clock());
n = (argc > 1) ? strtol(argv[1], NULL, 0) : 1;
while (n-- > 0) {
x = createNumb();
printf("%04d\n", x);
}
return 0;
}
Boolean operators evaluate to 1 when they are true and 0 otherwise. bb = (b >= a); is a short notation for:
bb = 0;
if (b >= a)
bb = 1;
If you want to compute an array of 4 numbers with the given constraint, you should pass a pointer to the destination array as an argument to creatNumb(). Here is a modified version with this approach:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void createNumb(int *dest) {
int a, b, c, d, bb, cc, dd;
a = rand() % 10;
b = rand() % 9;
c = rand() % 8;
d = rand() % 7;
bb = (b >= a);
cc = (c >= a) + (c >= b);
cd = (d >= a) + (d >= b) + (d >= c);
dest[0] = a;
dest[1] = b + bb;
dest[2] = c + cc;
dest[3] = d + dd;
}
int main(int argc, char *argv[]) {
int array[4];
srand(clock());
createNumb(array);
printf("%d%d%d%d\n", array[0], array[1], array[2], array[3]);
return 0;
}
Note that passing an array as a argument to a function actually passes a pointer to its first element: createNumb(array); is equivalent to createNumb(&array[0]);. This process is referred to as arrays decay into pointers in most expression contexts, it is somewhat confusing for beginners but allows for efficient argument passing.
The recursive function FastExp computes (a^n)(mod m) using the algorithm :
a^n = 1, if n=0;
a^n = [a^(n/2)]^2, if n is even; and
a^n = a(a^[(n-1)/2])^2 if n is odd.
Now I'm sure the algorithm is correct and I followed it exactly, but I get a segmentation fault when I try to run my code. Here's my code -
`#include <stdio.h>
/* function prototype */
int FastExp(int a, int n, int m);
/* There is no error in the main function */
int main()
{
int a, n, m;
printf("Enter three positive numbers a n m: ");
scanf("%d %d %d", &a, &n, &m);
printf("%d^%d(mod %d) is %d\n", a, n, m, FastExp (a, n, m));
return 0;
}
/*
* FastExp(a, 0, m) is 1.
* FastExp(a, 1, m) is a.
* x = FastExp(a, n/2, m)
* FastExp(a, n, m) is x2(mod m) if n is even
* FastExp(a, n, m) is x2a(mod m) if n is odd
*/
/* There is some error in this function */
int FastExp(int a, int n, int m)
{
int an;
if (n == 0)
{
an = 1;
return an;
}
//even
if (n % 2 == 0)
{
an = FastExp (a, n/2, m); // an = a^(n/2)
an = FastExp (an, 2, m); // an = [a^(n/2)]^2
return an;
}
// odd
if (n % 2 == 1)
{
an = FastExp (a, (n-1)/2, m); // an = a^[(n-1)/2]
an = FastExp (an, 2, m); // an = {a^[(n-1)/2]}^2
an = an*a;
return an;
}
return (an % m);
}
I'm guessing it runs into an infinite loop, but I'm not really sure how to correct this. Am I making some basic error? Can anyone explain how to correct it with the least number of instruction changes?
You have the recursive call FastExp (an, 2, m). That leads to infinite recursion.
It's infinite because in the recursive call n is even so you call FastExp (an, 2, m). And in that call n is even so you call FastExp (an, 2, m). And so on.
You fail to stop the recursion in the cases when n == 1 and n == 2.
I don't quite understand your code... From reading the comments for FastExpr, I arrive at this result, which is quite different. Am I missing something here?
/*
* FastExp(a, 0, m) is 1.
* FastExp(a, 1, m) is a.
* x = FastExp(a, n/2, m)
* FastExp(a, n, m) is x2(mod m) if n is even
* FastExp(a, n, m) is x2a(mod m) if n is odd
*/
int FastExp(int a, int n, int m)
{
int x;
if (n == 0) return 1;
if (n == 1) return a;
x = FastExpr(a, n / 2, m); // <-- Good. Converges to zero.
x *= x;
return (n & 1) ? ((x * a) % m) : (x % m);
}
I'm trying to hone my skills in C as well as get a better understanding of RSA, so I took it upon myself to try and make my own generator. I've generated both base prime numbers, p and q, calculated the value o = (p-1) * (q-1). These are working correctly. The next steps is where I'm having issues. I'm pretty close, but I can't seem to find the correct way to calculate the encryption and decryption factors of the 1 mod r value. Any help for generating this would be awesome. (or just write the code yourself and i can learn off that) Plus if there's any other issues let me know!
Here's my code:
#include<stdio.h>
#include<time.h>
#include"../hdr/test.h" //fake header just to satisfy my makefile
//Receives: number that was generated in main
//Returns: 1 for false, 0 for true
//Purpose: checks if the numbers is prime and returns 1 or 0
int isPrime(int number)
{
if (number <= 1)
return 0;
int i;
for (i=2; i<number; i++) {
if (number % i == 0)
return 0;
}
return 1;
}
/*Receives: an integer ((p-1) * (q-1))
Returns: integer (e)
Purpose: Generates the relatively prime number to ((p-1) * (q-1))*/
int gen_E(int o)
{
puts("Generating E...");
int e;
do {e = rand() % o;} while (GCD(e, o) != 1);
return e;
}
/*Receives: integer E and O from the main
Returns: newly calculated integer D
Purpose: Generates D for the private key*/
int gen_D(int e, int o)
{
puts("Generating D...");
int e = a;
int o = b;
int phin, d;
for (phin = 1; phin < o; phin ++)
for (d = 1; d < 998001; d ++)
if ((e * d) == (o * phin) + 1) return d;
}
/*Receives: integer E and O from main
Returns: greatest common divisor's remainder
Purpose: Calculate if the two numbers share a divisor.*/
int GCD(int e, int o)
{
int c;
while (e != 0) {
c = e; e = o%e; o = c;
}
return o;
}
int main()
{
puts("Generating Prime P...");
srand(time(NULL));
int p = rand() % 1000;
while (isPrime(p) != 1) {
p = rand() % 1000;
}
puts("Generating Prime Q...");
int q = rand() % 1000;
while (isPrime(q) != 1) {
q = rand() % 1000;
}
int n = p * q;
int o = (p - 1) * (q - 1);
int e = gen_E(o);
int d = gen_D(e, o);
printf("p: %d\nq: %d\nn: %d\no: %d\ne: %d\nd: %d\n", p, q, n, o, e, d);
printf("KU = {%d, %d}\n", e, n);
printf("KR = {%d, %d}\n", d, n);
}
You will need a function to compute GCD (greatest common divider) of two numbers. After that, choose random e such that GCD(e,o) == 1.
Of course in practice it's probably more complicated than that but for homework it's fine.
how to get the value of an integer x, indicated by x!, it is the product of the numbers 1 to x.
Example: 5! 1x2x3x4x5 = 120.
int a , b = 1, c = 1, d = 1;
printf("geheel getal x = ");
scanf("%d", &a);
printf("%d! = ", a);
for(b = 1; b <= a; b++)
{
printf("%d x ", c);
c++;
d = d*a;
}
printf(" = %d", d);
how to get the som of an integer x, indicated by x!, is the product of the numbers 1 to x.
Did you mean factorial of x ?
Change d = d*a; to d = d*b inside the loop
You can simply do:
for(b = 1; b <= a; b++) {
d *= b;
}
// d now has a!
This is the optimal implementation in size and speed:
int factorial(int x)
{
static const int f[13] = { 1, 1, 2, 6, 24, 120, /* ... */ };
if ((unsigned)x < (sizeof f/sizeof f[0])) return f[x];
else return INT_MAX+1; /* or your favorite undefined behavior */
}
Hint: x! (x factorial) does not fit in an int except for very very small values of x.
Try
d = d * b;
instead of
d = d * a
and it should work fine
You actually have a lot of redundant code there, that might be why you did not spot the error yourself.
To calculate the factorial, you only need the accumulator (d in the above code) and the input (a). Why?
My code is not good as other but it works for me:
#include <iostream>
using namespace std;
unsigned int fattoriale (int n){
if (n == 1){
return 1;
}
else {
return n * fattoriale(n-1);
}
}
int main() {
int tmp, num;
cin >> num;
tmp = fattoriale(num);
cout << "Stampo il fattoriale del numero inserito: " << tmp << endl;
}
int factorial(int x)
{
int f;
if (x == 0)
{
f = 1;
}
else if (x > 0)
{
f = x*factorial(x-1);
}
return f;
}
int main()
{
int n = 0;
cout << factorial(n);
return 0;
}