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;
}
Related
I am trying to calculate value of sin(x) in C but I am getting black screen in code:block after execution, its taking long for compilation and execution.
#include<stdio.h>
float mult(float x, int m, int i) {
float a = x;
if (i == m) {
return x;
} else {
i++;
a = a * mult(x, m, i);
return a;
}
}
int fact(int m) {
printf("%d! ", m); fflush(stdout);
int b;
if (m == 1) {
return 1;
} else {
b = m * fact(m - 1);
return b;
}
}
float term(float x, int m) {
float a = 0, b = 0, c = 0;
int i = 0;
a = mult(x, m, i);
b = fact(m);
c = a / (1.0 * b);
return c;
}
float sinof(float x, int m, int n) {
float b = 0;
if (m >= 10) {
return (0);
} else {
printf("......%d ", m); fflush(stdout);
b = term(x, m);
m = m + 2;
n = -n;
b = b + (n * sinof(x, m, n));
return b;
}
}
int main() {
float x = 0, sin = 0;
int m = 1, n = 1;
printf("Enter the angle in radians:");
scanf("%f", &x);
sin = sinof(x, m, n);
printf("%f", sin);
}
I hope the logic is correct.
m is odd. Below fails to stop recursion.
if(m==10){ // Never true
return(0);
} else{
b=term(x,m);
m=m+2;n=-n; // ***********
b=b+(n*sinof(x,m,n));
return b;
}
I recommend OP get own code working first. There are various other issues.
For a simplified recursive sine(), mouse over to see.
static double my_sin_helper(double xx, double term, unsigned n) {
if (term + 1.0 == 1.0) {
return term;
}
return term - my_sin_helper(xx, xx *term / ((n + 1) * (n + 2)), n + 2);
}
// valid for [-pi/2 + pi/2]
double my_sin_primary(double x) {
return x * my_sin_helper(x * x, 1.0, 1);
}
I am currently doing exercices on Kattis and I meet a problem with I think the float.
I must compare the size of matchstick with the size of box
Sibice problem on Kattis.com
Here is a picture of the exercise
I can make examples but when I submit I past only the first two...
Here is a picture of my submission
I don't have a trace or explication for know my errors... I tried to change the type of my variables but there is no change... I think the problems is float but I need it.
Here is my code
#include <stdio.h>
void sibice(float n, float w, float h)
{
float v = 0;
for(float i = 0; i != n; i += 1) {
scanf("%f", &v);
if(v < w + h / 2)
printf("DA\n");
if(v == w + h / 2)
printf("DA\n");
if(v > w + h / 2) {
printf("NE\n");
}
}
}
int main(void)
{
float n = 0;
float w = 0;
float h = 0;
scanf("%f %f %f", &n, &w, &h);
sibice(n, w, h);
return (0);
}
Do you think that I can optimize my code ?
Incorrect test
If a match can fit is a more like v*v <= h*h + w*w than v < w + h / 2. Can it diagonally fit?
See Pythagorean theorem
#include <math.h>
...
float hyp = hypotf(h,w); // sqrt(h*h + w*w)
for(float i = 0; i != n; i += 1) {
scanf("%f", &v);
// if(v < w + h / 2)
if(v < hyp)
No need for 3 tests
One test is sufficient.
if(v <= hyp) {
printf("DA\n");
} else {
printf("NE\n");
}
Integer math
As all calculations are whole numbers, code could use int only math.
void sibice(int n, int w, int h) {
int hyp2 = h*h + w*w;
for (int i = 0; i != n; i += 1) {
int v;
scanf("%d", &v);
if (v*v <= hyp2)
...
Other issues may exist
Why do you need to use float? With these changes the code passes the tests:
#include <stdio.h>
#include <stdlib.h>
void sibice(int n, int w, int h)
{
int v;
int result;
for (int i = 0; i != n; i += 1) {
result = scanf("%d", &v);
if (1 != result)
exit(1);
if (v * v <= w * w + h * h)
printf("DA\n");
else
printf("NE\n");
}
}
int main(void)
{
int n = 0;
int w = 0;
int h = 0;
int result = 0;
result = scanf("%d %d %d", &n, &w, &h);
if (3 != result)
return 1;
sibice(n, w, h);
return (0);
}
For this assignment I am supposed to use the debugger in Visual Studios, I kind of understand how to use it but i cant figure it out completely. For the first part of the code, it asks for all values of a,b, and c. I put my debugger to start right before it starts and then right after it ends. I run it through using the F10 key. I go through it once and I get a=6, b=3, c=6. Then once I go through it again i get different values, however I want to view those values as a list. Is that possible?
//THIS IS THE CODE.
#include<stdio.h>
void func1(int a, int b, int c)
{
//Track all values of a, b, and c
printf("%d %d %d\n",a,b,c);
a = b + b;
printf("%d %d %d\n",a,b,c);
}
int func2(int x)
{
//Track all values of x
printf("%d\n",x);
for (x = 7; x < 12; x += 1)
{
printf("%d", x + 10);
}
return(x);
}
int func3(int x)
{
x = x + 51;
return(x);
}
int main()
{
int a,b,c;
//Track each array index value
int arr[5];
a = 7;
b = 3;
c = 3;
func1(5, 3, 6);
func2(c);
b = func2(c);
for (c = 0; c < 5; c += 1)
{
arr[c] = c + 2;
}
for (b = 22; b > 7; b += -1)
{
arr[b + func3(a)] = a + b + c;
printf("%d\n", b);
}
for (b = 0; b < 5; b += 1)
{
printf("%d\n", arr[b]);
}
return(0);
}
arr[b + func3(a)]
Before debugging further fix the bug in the code.
Here you have array out of bound access which will lead to undefined behavior.
You are trying to access arr[22 + x] where as the size of the array is 5.
I'm trying to implement the Feige Fiat Shamir Identification Scheme in C (Arduino) and it works, but only when e = 0. When e = 1 it doesn't work.
How can I make it work?
#include <Wire.h>
int getGCD(int a, int b)
{
int c;
while (a != 0)
{
c = a;
a = b % a;
b = c;
}
return b;
}
int getCoprime(int n)
{
int coprime;
do
{
coprime = random(1, n);
}
while (getGCD(n, coprime) != 1);
return coprime;
}
//Preparation
int n = 7 * 3;
int s = getCoprime(n);
int v = (s * s) % n;
void loop ()
{
e = random(0, 2);
r = random(1, n);
int y = (r * (int)pow(s, e)) % n;
int x = (r * r) % n;
int ysqmodn = y * y % n;
int test = (x * (int)pow(v, e)) % n;
if(ysqmodn == test)
{
Serial.print("The current ICC matches. \n");
}
else
{
Serial.print(String(e));
Serial.print("\n");
}
delay(500);
}
It does work when e==1. When e==0 the computation is trivial, since s and v fall out due to power of 0 always being 1. This is the code copied and altered only enough to get it to compile.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
int random (int low, int high) {
return low + rand() % (high - low);
}
int getGCD(int a, int b) {
int c;
while (a != 0)
{
c = a;
a = b % a;
b = c;
}
return b;
}
int getCoprime(int n) {
int coprime;
do
{
coprime = random(1, n);
}
while (getGCD(n, coprime) != 1);
return coprime;
}
int main(void) {
int e, x, y, r, n, s, v, test, ysqmodn;
srand((unsigned)time(NULL));
n = 7 * 3;
s = getCoprime(n);
v = (s * s) % n;
e = random(0, 2);
r = random(1, n);
printf("n=%d, s=%d, e=%d, r=%d\n", n,s,e,r);
y = (r * (int)pow(s, e)) % n;
x = (r * r) % n;
ysqmodn = y * y % n;
test = (x * (int)pow(v, e)) % n;
if(ysqmodn == test)
printf("The current ICC matches. \n");
else
printf("%d\n", e);
return 0;
}
Sample results:
n=21, s=2, e=1, r=2
The current ICC matches.
n=21, s=11, e=0, r=12
The current ICC matches.
n=21, s=8, e=1, r=14
The current ICC matches.
n=21, s=17, e=1, r=13
The current ICC matches.
n=21, s=1, e=0, r=9
The current ICC matches.
n=21, s=4, e=0, r=13
The current ICC matches.
float a, b;
float sa() { return a;};
int main() {
a = 10;
b = sa();
printf("%f", b);
return 0;
}
This is a simplified version of my code.
I believe the program should print 10 but it gives me really small numbers like -65550, not always the same but very alike.
I have used the debugger to check the value of variabe a right before it is returned and it is 10, so the function returns 10, but b is set to something like -65550. I don't understand why this happens.
I'd appreciate some intell.
Thanks in advance.
Here is the full code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
int dimensiuni, nrBitiSolutie, bitiPeDimensiune, gasitInbunatatire, nrRulari;
float limInf, limSup, precizie, valoareFunctie, minim, minimNou, T;
char solutie[100000];
float solutieReala[100];
void generateRandomSolution();
void bitesToFloat();
void rastrigin();
void rosenbrock();
float nextFirstFit();
float nextBestFit();
void main() {
int k;
T = 10;
gasitInbunatatire = 1;
srand ( time(NULL) );
printf("Introduceti numarul de dimensiuni: ");
scanf("%d", &dimensiuni);
printf("Introduceti limita inferioara si cea superioara: ");
scanf("%f%f", &limInf, &limSup);
printf("Introduceti precizia: ");
scanf("%f", &precizie);
//calculam numarul de biti necesari ca sa reprezentam solutia
nrBitiSolutie = dimensiuni * ceil(log(limSup-limInf * pow(10, precizie)))/log(2.0);
bitiPeDimensiune = nrBitiSolutie/dimensiuni;
//generam o solutie random
generateRandomSolution();
bitesToFloat();
rastrigin();
minim = valoareFunctie;
printf("Pornim de la %f\n", minim);
while( (nrRulari < 10000) && (T > 0.001)) {
minimNou = sa(); //error occurs here. sa() returns about 200 but minimNou is set to -65550
if (minimNou < minim) {
printf("Minim nou: %f\n", minimNou);
minim = minimNou;
T *= 0.995;
}
nrRulari++;
}
printf("Minimul aproximat: %f\n", minim);
system("pause");
}
void generateRandomSolution() {
int l;
for (l = 0; l < nrBitiSolutie; l++) solutie[l] = rand()%2;
}
void bitesToFloat() {
int i, parcurse = 1, gasite = 0;
int variabila = 0;
float nr;
for (i = 0; i < nrBitiSolutie; i++) {
variabila = variabila<<1 | (int)solutie[i];
if(parcurse == bitiPeDimensiune) {
nr = (float)variabila / (float)pow(2, bitiPeDimensiune);
nr *= limSup-limInf;
nr += limInf;
nr *= pow(10, precizie);
nr = (int)nr;
nr /= pow(10, precizie);
parcurse = 0;
solutieReala[gasite++] = nr;
variabila = 0;
}
parcurse++;
}
}
void rastrigin() {
int i;
valoareFunctie = 10 * dimensiuni;
for (i = 0; i < dimensiuni; i++) {
valoareFunctie += pow((float)solutieReala[i], 2) - 10 * (float)cos(2 * 3.14 * (float)solutieReala[i]);
}
}
void rosenbrock() {
int i;
valoareFunctie = 0;
for (i = 0; i < dimensiuni - 1; i++) {
valoareFunctie += 100 * pow((solutieReala[i+1] - pow(solutieReala[i], 2)), 2) + pow((1-solutieReala[i]), 2);
}
}
float sa() {
int j;
for (j = 0; j < nrBitiSolutie; j++) {
solutie[j] = solutie[j] == 0 ? 1 : 0;
bitesToFloat();
rastrigin();
if (valoareFunctie < minim) return valoareFunctie;
else if ( (rand()/INT_MAX) < exp((minim - valoareFunctie)/T) )
return valoareFunctie;
else solutie[j] = solutie[j] == 0 ? 1 : 0;
}
return minim;
}
I have marked where the error occurs with error occurs here comment
You simplified the code incorrectly. In your simplification, you defined sa() before calling it. But in your full program, you call sa() before defining it. In the absence of a declaration, functions are assumed to return int. Since your function actually returns a float, the result is undefined. (In this case, you will read a garbage value from the top of the floating point stack and then the floating point stack will underflow, and things go downhill from there.)