i'm trying to compute "2^0 + 2^1 + 2^2 + ... + 2^14", using the following program(i'm a newbie and can only compute a exponent by multiply itself a certain times). The result should be 32767, but i ran it and got 270566475, i thought for long but can't figure out why...
#include <stdio.h>
int main(void)
{
int i, e, exponent, sum;
e = 1;
exponent = 1;
sum = 1;
for (i = 1; i <=14; i++)
{
for (e = 1; e <= i; e++)
{
exponent *= 2;
}
sum += exponent;
}
printf("%d\n", sum);
return 0;
}
So what's wrong with this??? Thanks!!!
You don't need the inner loop. Just execute exponent *= 2 once, directly inside the outer loop. BTW, I think you have to do it after the sum += ....
Also, you could start with sum = 0 and i = 0, which is closer to the math you described.
Look at your inner loop by itself. It's trying to calculate, for one specific value of i, 2^i.
But exponent does not start at 1 every time. So you go into that loop with exponent already some very large value.
for (i = 1; i <=14; i++)
{
exponent = 1;
for (e = 1; e <= i; e++)
{
exponent *= 2;
}
sum += exponent;
}
Now you've reset exponent (which, to be clear, isn't the exponent at all but the calculated result) for each new power of 2.
If you have right to create a function it better to do it like this with a recursive function :
#include <stdio.h>
int power(int x, int exp) {
if (exp == 0)
return 1;
else
return x * power(x, exp-1);
}
int main (int argc, const char * argv[])
{
int i;
int sum = 0;
for (i = 0; i <= 14; i++) {
sum += power(2, i);
}
printf("%d",sum);
return 0;
}
I hope it helps.
You just need one loop because each you already have the result of n-1 value. I had correct your code it works.
#include <stdio.h>
int main (int argc, const char * argv[])
{
int i, e, exponent, sum;
e = 1;
exponent = 1;
sum = 1;
for (i = 1; i <= 14; i++)
{
exponent *= 2;
sum += exponent;
}
printf("%d\n", sum);
return 0;
}
Both codes work
Related
I can’t solve this equation.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int n, result, sum, product;
sum = 0; product = 1, result = 0;
for (int n = 1; n <= 20; n++) {
for (int i = 1; i <= n; i++) {
sum = sum + ((i - n) / (i + n));
product *= sum;
result = sum + product;
}
}
printf("result::%d",result);
return 0;
}
You are on the right track, but note these problems:
you should use double arithmetics for the computation and values, otherwise the result will be meaningless.
you should initialize sum to 0 before the inner loop
you should move the product outside the inner loop
n is redefined in the outer for loop
result is probably not needed.
Here is a modified version:
#include <stdio.h>
int main() {
double product = 1.0;
for (int n = 1; n <= 20; n++) {
double sum = 0.0;
for (int i = 1; i <= n; i++) {
sum += (double)(i - n) / (double)(i + n);
}
product *= sum;
}
printf("result: %f\n", product);
return 0;
}
The above direct translation of the formula outputs -0.000000. The explanation is simple: if you look at the formula, you will see that the first term of the product for n=1 is sum for i from 1 to 1 of (i - n) / (i + n), which is (1 - 1) / (1 + 1), that is 0. Multiplying that by any finite quantity will stay invariably null.
Hence the formula can be solved algebraically and produce a much simplified version. A good algorithm beats any brute force approach:
#include <stdio.h>
int main() {
printf("result: 0\n");
return 0;
}
145 = sum of 1! + 4! + 5!. I need to write a program in C, that finds the 5 digit numbers that have this property.
I have written the code successfully for the 3 digits. I used the same code for 5 digits, but it cant find any number.
I would like to help me with my solution, in order for me to see where am I wrong.
#include <stdio.h>
int factorial(int n);
main() {
int pin[5];
int q = 1;
int w = 0;
int e = 0;
int r = 0;
int t = 0;
int result = 0;
int sum = 0;
for (q = 1; q <= 9; q++) {
for (w = 0; w <= 9; w++) {
for (e = 0; e <= 9; e++) {
for (r = 0; r <= 9; r++) {
for (t = 0; t <= 9; t++) {
pin[0] = q;
pin[1] = w;
pin[2] = e;
pin[3] = r;
pin[4] = t;
int factq = factorial(q);
int factw = factorial(w);
int facte = factorial(e);
int factr = factorial(r);
int factt = factorial(t);
sum = factq + factw + facte + factr + factt;
result = 10000 * q + 1000 * w + 100 * e + 10 * r + t * 1;
if (sum == result)
printf("ok");
}
}
}
}
}
}
int factorial(int n) {
int y;
if (n == 1) {
y = 1;
} else if (n == 0)
y = 0;
else {
y = n * factorial(n - 1);
return y;
}
}
Your factorial function doesn't return a value in all cases:
int factorial (int n) {
int y;
if (n==1) {
y = 1;
}
else
if (n==0)
y = 0;
else {
y = n * factorial(n-1);
return y;
}
}
It only returns a value when it makes a recursive call. The base cases don't return anything. Failing to return a value from a function and then attempting to use that value invokes undefined behavior.
Move the return statement to the bottom of the function so it gets called in all cases. Also the value of 0! is 1, not 0.
int factorial (int n) {
int y;
if (n<=1)
y = 1;
else
y = n * factorial(n-1);
return y;
}
Also, when you find the target value you probably want to print it:
printf("ok: %d\n", result);
dbush's answer is accurate in pointing out why your code didn't work. This is an alternative solution to reduce the amount of calculation done by your program by not re-calculating the factorial of each numeral every step of the way. The way your program currently works, it winds up being around 500,000 calls to the factorial function from your nested loop, and then in turn recursively calls the function on average 4ish times for each call from the nested loop, so that's around 2 million calls to factorial. The more digits you tack on, the faster that number grows and more expensive it gets. To avoid all these recalculations, you can create a Look-up table that stores the factorial of the numerals [0-9] and just looks them up as needed.
You can calculate these values ahead of time and initialize your LUT with these values, but if hypothetically you wanted them to be calculated by the program because this is a programming assignment where you can't cut out such a step, it is still pretty trivial to populate the LUT.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
void populate_lut(uint32_t *lut);
int main(void) {
// lut is an array holding the factorials of numerals 0-9
uint32_t lut[10];
populate_lut(lut);
for (uint8_t q = 1; q <= 9; q++) {
for (uint8_t w = 0; w <= 9; w++) {
for (uint8_t e = 0; e <= 9; e++) {
for (uint8_t r = 0; r <= 9; r++) {
for (uint8_t t = 0; t <= 9; t++) {
// now instead of calculating these factorials, just look them up in the look-up table
uint32_t sum = lut[q] + lut[w] + lut[e] + lut[r] + lut[t];
uint32_t result = 10000 * q + 1000 * w + 100 * e + 10 * r + t * 1;
if (sum == result) {
printf("Solution: %" PRIu32 "\n", result);
}
}
}
}
}
}
}
// populate your lookup table with the factorials of digits 0-9
void populate_lut(uint32_t *lut) {
lut[0] = 1;
lut[1] = 1;
for(uint8_t i = 2; i < 10; ++i) {
lut[i] = lut[i-1] * i;
}
}
Following needs to be calculated (iterative und recursive Solution)
Sum = 1 – 1/2 + 1/3 – 1/4 + - . . . 1/n (n > 0) with float reihe (int n)
We have the following so far:
#include <stdio.h>
float reihe(int n)
{
float sum = 0;
if (n = 1)
sum = 1;
else
{
for (int i = 1; i < n; i++)
{
sum += (1 / i) - (1 / (1 + i));
}
}
return sum;
}
int main(void)
{
float z;
z = reihe(5);
printf("%d", z);
return 0;
}
Would appreciate any of your help. Have a good day.
What about something like this? Not tested, but it compiles and runs...
BTW/ take a close look at the use of 1.0. If you use 1 it is interpreted as an integer and not a float and you division is always rounded to 1 or 0 and you lose all decimal values...
float reihe(int n)
{
float sum = 0;
float base = 1.0;
for (int i = 1; i <= n; i++) {
if ( i % 2 ) {
sum += base/i;
}
else {
sum -= base/i;
}
}
return sum;
}
I'm trying to approximate Euler's number in C using a loop that terminates when the difference between two successive values of e is less than 0.0000001. The value I get is 2.99.. I tried setting it up so that with each iteration, e will be compared with the previous value of itself (held in e1) and if the difference is greater than 0.0000001 it will add another term 1/(n!). What's the issue? I'm new to programming so any advice/critiquing is appreciated.
#include <stdio.h>
int main()
{
float e1 = 0, e2 = 1;
int n = 1, nfact;
while ((e2 - e1) > 0.0000001)
{
e1 = e2;
nfact = 1;
for (int count = 1; count < n; count++)
{
nfact = n * count;
}
n = n + 1;
e2 = e1 + (1.0 / nfact);
}
printf("Approximated value of e = %f", e2);
return 0;
}
nfact = 1;
for (int count = 1; count < n; count++)
{
nfact = n * count;
}
won´t calculate n!.
nfact gets a completely new value every iteration.
Surely you mean
nfact = 1;
for (int count = 2; count <= n; count++)
{
nfact *= count;
}
This is not how you calculate the factorial of a number:
for (int count = 1; count < n; count++)
{
nfact = n * count;
}
Notice that you always assign to nfact on each iteration to the value of n*count, obliterating the previous value of nfact. This piece of code is equivalent to:
nfact = n*(n-1);
Since that's the last value of count.
I think you wanted this instead:
nfact = n;
for (int count = n-1; count > 0; count--)
{
nfact = nfact * count;
}
This is my code for
estimates the value of the mathematical constant e by using the formula:
e = 1 + 1/1! + 1/2! + 1/3! + ....
#include <stdio.h>
int main(void) {
int n = 0; /* loop counter for accuracy */
int accuracy = 10; /* current n factorial */
int fact = 1; /* degree of accuracy */
double e = 0; /* current estimated value of e */
/* loop until degree of accuracy */
while (n <= accuracy) {
if (n == 0) {
fact *= 1;
} else {
fact *= n;
}
e += 1.0 / fact;
++n;
}
printf("e is %f", e);
return 0;
}
Write a program that will find the largest number smaller than N that is totally different from a given number X. One number is totally different from other only if it doesn't contain any of the digits from the other number. N and X are read from standard input. The problem should be solved without the use of arrays.
Example Input 1: 400 897
Example Output 1: 366
Example Input 2: 1000 1236498
Example Output 2:777
No it's not homework, it was on one of the midterms and it's been killing me. I though about taking the first numbers last digit with %10 then taking the second numbers digit with %10 comparing them but...I just can't get it to work...I ended up with an endless loop...I just don't understand how to get every digit of the numbers and compare them to the other number.
#include <stdio.h>
int main () {
int N, X, num_N, num_X, i, lastDigit_N, lastDigit_X, flag, smaller_than_N;
scanf("%d%d", &N, &X);
smaller_than_N = N - 1;
for (i = smaller_than_N; i > 0; i--) {
num_N = i;
num_X = X;
flag = 0;
while (num_N > 0) {
lastDigit_N = num_N % 10;
while (num_X > 0) {
lastDigit_X = num_X % 10;
if (lastDigit_N == lastDigit_X) {
break;
}
else {
flag = 1;
}
num_X /= 10;
}
num_N /= 10;
}
if(flag) {
printf("%d", i);
break;
}
}
return 0;
}
You could build a bitmask for your numbers showing the digits which are contained.
uint16_t num2bitmask(int number)
{
uint16_t result = 0;
while (number) {
int digit = number % 10;
number /= 10;
result |= (1 << digit);
}
return result;
}
With this function, you can create your bitmask for X and then iterate from N-1 down to 1 until you find a value which doesn't have any bits in common with the other value.
If you have a number with digits d_1, d_2, ..., d_n, and you're allowed to use digits in the set D, then possible solutions look like:
d_1, ..., d_{i-1}, max(d in D | d < d_i), max(d in D), ..., max(d in D).
That is, the digits are the same up to some point, then the next digit is as large as possible while being below the input digit, then the rest are just as large as possible.
Not all these "solutions" will be valid, but if you iterate through them in reverse order (there's exactly n for an input number of size n), the first valid one you find is the answer.
Some code, including tests:
#include <stdio.h>
int digit_length(int a) {
int r = 0;
while (a) {
a /= 10;
r += 1;
}
return r;
}
int get_digit(int a, int k) {
while (k--) a /= 10;
return a % 10;
}
int largest_different(int a, int b) {
int lena = digit_length(a);
int invalid = b ? 0 : 1;
for (; b; b /= 10) invalid |= 1 << (b % 10);
int max_valid = 9;
while (max_valid >= 0 && (invalid & (1 << max_valid)))
max_valid--;
if (max_valid == -1) return -1;
for (int i = 0; i < lena; i++) {
int d = get_digit(a, i) - 1;
while (d >= 0 && (invalid & (1 << d)))d--;
if (d < 0) continue;
int solution = 0;
for (int k = lena - 1; k >= 0; k--) {
solution *= 10;
solution += (k < i ? max_valid : k > i ? get_digit(a, k) : d);
}
return solution;
}
return -1;
}
int main(int argc, char *argv[]) {
struct {int n; int x; int want;} examples[] = {
{400, 897, 366},
{1000, 1236498, 777},
{998, 123, 997},
};
int error = 0;
for (int i = 0; i < sizeof(examples) / sizeof(*examples); i++) {
int got = largest_different(examples[i].n, examples[i].x);
if (got != examples[i].want) {
error = 1;
printf("largest_different(%d, %d) = %d, want %d\n",
examples[i].n, examples[i].x, got, examples[i].want);
}
}
return error;
}
There's not always a solution. In that case, the function returns -1.