This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
why is = n! / ((n-k)!*k!) not printing?
Also will this code solve the problem below?
stuck.
"The number of combinations of n things taken k at a time as an integer"
A little more clarification: "For example, the combinations of four items a,b,c,d taken three at a time are abc, abd, acd, and bcd. In other words, there are a total of four different combinations of four things "taken three at a time"."
#include <stdio.h>
#include <math.h>
int main (void)
{
int z = 0, n_in, k_in, k = 0, n = 0, result, nfr = 0, kfr = 0;
do
{
printf("Enter the number of items in the list (n):");
scanf("%d*c", &n_in);
if (n_in>1 && n_in<11)
{
printf("Enter the number of items to choose (k)");
scanf("%d*c", &k_in);
if (k_in>0 && k_in<5)
{
if (k_in <= n_in)
{
k_in = k;
n_in = n;
result = n! / ((n-k)!*k!);
z = 1;
}
else
printf("?Please Try again k must be less than n \n");
}
else
printf("?Invalid input: Number must be between 1 and 4 \n");
}
else
printf("?Invalid input: Number must be between 1 and 10 \n");
} while (z == 0);
result = (nfr / (nfr * kfr));
printf("k value = %d n value = %d the result is %d", nfr, kfr, result);
return 0;
}
This line:
result = n! / ((n-k)!*k!);
...is not valid C code. ! in C means "not".
You will need to provide a factorial function so that you can call:
result = factorial(n) / (factorial(n-k) * factorial(k));
! is not the NOT operator in C. Use this factorial function instead.
int factorial(int n)
{
return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}
So your calculation would be:
result = factorial(n) / (factorial(n-k)*factorial(k));
There are probably faster ways to do it, but this is readable.
Also, this line
result = (nfr / (nfr * kfr));
Does not make any sense to me, since both nfr and kfr are zero, but I guess you wanted to get the code to compile, before completing the logic.
EDIT:
complete code should look like this:
#include <stdio.h>
#include <math.h>
int factorial(int n)
{
return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}
int main (void)
{
int z = 0, n_in, k_in, k = 0, n = 0, result, nfr = 0, kfr = 0;
do
{
printf("Enter the number of items in the list (n):");
scanf("%d*c", &n_in);
if (n_in>1 && n_in<11)
{
printf("Enter the number of items to choose (k)");
scanf("%d*c", &k_in);
if (k_in>0 && k_in<5)
{
if (k_in <= n_in)
{
k_in = k;
n_in = n;
result = factorial(n) / (factorial(n-k)*factorial(k));
//result = n! / ((n-k)!*k!);
z = 1;
}
else
printf("?Please Try again k must be less than n \n");
}
else
printf("?Invalid input: Number must be between 1 and 4 \n");
}
else
printf("?Invalid input: Number must be between 1 and 10 \n");
} while (z == 0);
//result = (nfr / (nfr * kfr));
printf("k value = %d n value = %d the result is %d\n", nfr, kfr, result);
return 0;
}
Output:
~/so$ gcc test.cc
~/so$ ./a.out
Enter the number of items in the list (n):3
Enter the number of items to choose (k)2
k value = 0 n value = 0 the result is 1
~/so$
Related
The function should take the address of the integer and modify it by inserting zeros between its digits. For example:
insert_zeros(3) //3
insert_zeros(39) //309
insert_zeros(397) //30907
insert_zeros(3976) //3090706
insert_zeros(39765) //309070605
My code:
#include <stdio.h>
#include <math.h>
void insert_zeros(int* num);
int main() {
int num;
printf("Enter a number:");
scanf("%d", num);
insert_zeros(&num);
printf("Number after inserting zeros: %d", num);
return 0;
}
void insert_zeros(int* num){
int count = 0;
int tmp = *num;
//Count the number of digits in the number
while(tmp != 0){
tmp /= 10;
count++;
}
//calculating the coefficient by which I will divide the number to get its digits one by one
int divider = (int)pow(10, count-1);
int multiplier;
tmp = *num;
*num = 0;
/*
The point at which I'm stuck
Here I tried to calculate the degree for the number 10
(my thought process and calculations are provided below)
*/
(count >= 3)? count += (count/2): count;
//the main loop of assembling the required number
while (count >= 0){
multiplier = (int)pow(10, count); //calculating a multiplier
*num += (tmp / divider) * multiplier; //assembling the required number
tmp %= divider; //removing the first digit of the number
divider /= 10; //decreasing divider
count -= 2; //decreasing the counter,
//which is also a power of the multiplier (witch is 10)
}
}
My idea consists of the following formula:
For number "3" I shold get "30" and it will be:
30 = (3 * 10^1) - the power is a counter for number "3" that equals 1.
For number "39" it will be "309":
309 = (3 * 10^2) + (9 * 10^1)
For number "397" it will be "30907":
30907 = (3 * 10^4) + (9 * 10^2) + (7 * 10^0)
For number "3976" it will be "3090706":
3090706 = (3 * 10^6) + (9 * 10^4) + (7 * 10^2) + (6 * 10^0) - with each iteration power is decreasing by 2
For number "39765" it will be "309070605":
309070605 = (3 * 10^8) + (9 * 10^6) + (7 * 10^4) + (6 * 10^2) + (5 * 10^0)
And so on...
For a 3-digit number, the start power should be 4, for a 4-digit number power should be 6, for a 5-digit it should be 8, for 6-digit it should be 10, etc.
That algorithm works until it takes a 5-digit number. It outputs a number like "30907060" with an extra "0" at the end.
And the main problem is in that piece of code (count >= 3)? count += (count/2): count;, where I tried to calculate the right power for the first iterating through the loop. It should give the right number to which will be added all the following numbers. But it only works until it gets a 5-digit number.
To be honest, so far I don't really understand how it can be realized. I would be very grateful if someone could explain how this can be done.
As noted in comments, your use of scanf is incorrect. You need to pass a pointer as the second argument.
#include <stdio.h>
#include <math.h>
int main(void) {
int num;
scanf("%d", &num);
int num2 = 0;
int power = 0;
while (num > 0) {
num2 += (num % 10) * (int)pow(10, power);
num /= 10;
power += 2;
}
printf("%d\n", num2);
return 0;
}
There's an easy recursive formula for inserting zeros: IZ(n) = 100*IZ(n/10) + n%10.
That gives a very concise solution -- here the test cases are more code than the actual function itself.
#include <stdio.h>
#include <stdint.h>
uint64_t insert_zeros(uint64_t n) {
return n ? (100 * insert_zeros(n / 10) + n % 10) : 0;
}
int main(int argc, char **argv) {
int tc[] = {1, 12, 123, 9854, 12345, 123450};
for (int i = 0; i < sizeof(tc)/sizeof(*tc); i++) {
printf("%d -> %lu\n", tc[i], insert_zeros(tc[i]));
}
}
Output:
1 -> 1
12 -> 102
123 -> 10203
9854 -> 9080504
12345 -> 102030405
123450 -> 10203040500
Adapting some code just posted for another of these silly exercises:
int main() {
int v1 = 12345; // I don't like rekeying data. Here's the 'seed' value.
printf( "Using %d as input\n", v1 );
int stack[8] = { 0 }, spCnt = -1;
// Peel off each 'digit' right-to-left, pushing onto a stack
while( v1 )
stack[ ++spCnt ] = v1%10, v1 /= 10;
if( spCnt == 0 ) // Special case for single digit seed.
v1 = stack[ spCnt ] * 10;
else
// multiply value sofar by 100, and add next digit popped from stack.
while( spCnt >= 0 )
v1 = v1 * 100 + stack[ spCnt-- ];
printf( "%d\n", v1 );
return 0;
}
There's a ceiling to how big a decimal value can be stored in an int. If you want to start to play with strings of digits, that is another matter entirely.
EDIT: If this were in Java, this would be a solution, but the problem is in C, which I'm not sure if this can convert to C.
This may be a lot easier if you first convert the integer to a string, then use a for loop to add the zeros, then afterward reconvert to an integer. Example:
int insert_zeros(int num) {
String numString = Integer.toString(num);
String newString = "";
int numStringLength = numString.length();
for (int i = 0; i < numStringLength; i++) {
newString += numString[i];
// Only add a 0 if it's not the last digit (with exception of 1st digit)
if (i < numStringLength - 1 || i == 0) newString += '0';
}
return Integer.parseInt(newString);
}
I think this should give you your desired effect. It's been a little bit since I've worked with Java (I'm currently doing JavaScript), so I hope there's no syntax errors, but the logic should all be correct.
I'm facing some difficulties in the last few days while trying to finish the following task, I hope you guys can assist :
I'm given a single number N, and I'm allowed to perform any of the two operations on N in each move :
One - If we take 2 integers where N = x * y , then we can change the value of N to the maximum between x and y.
Two - Decrease the value of N by 1.
I want to find the minimum number of steps to reduce N to zero.
This is what I have so far, I'm not sure what is the best way to implement the function to find the divisor (someFindDevisorFunction), and if this 'f' function would actually produce the required output.
int f(int n)
{
int div,firstWay,secondWay;
if(n == 0)
return 0;
div = SomefindDivisorFunction(n);
firstWay = 1 + f(n-1);
if(div != 1)
{
secondWay = 1 + f(div);
if (firstWay < secondWay)
return firstWay;
return secondWay;
}
return firstWay;
}
For example, if I enter the number 150 , the output would be :
75 - 25 - 5 - 4 - 2 - 1 - 0
I see this a recursive or iterative problem.
OP's approach hints at recursive.
A recursive solution follows:
At each step, code counts the steps of the various alternatives:
steps(n) = min(
steps(factor1_of_n) + 1,
steps(factor2_of_n) + 1,
steps(factor3_of_n) + 1,
...
steps(n-1) + 1)
The coded solution below is inefficient, but it does explore all possibilities and gets to the answer.
int solve_helper(int n, bool print) {
int best_quot = 0;
int best_quot_score = INT_MAX;
int quot;
for (int p = 2; p <= (quot = n / p); p++) {
int rem = n % p;
if (rem == 0 && quot > 1) {
int score = solve_helper(quot, false) + 1;
if (score < best_quot_score) {
best_quot_score = score;
best_quot = quot;
}
}
}
int dec_score = n > 0 ? solve_helper(n - 1, false) + 1 : 0;
if (best_quot_score < dec_score) {
if (print) {
printf("/ %d ", best_quot);
solve_helper(best_quot, true);
}
return best_quot_score;
}
if (print && n > 0) {
printf("- %d ", n - 1);
solve_helper(n - 1, true);
}
return dec_score;
}
int main() {
int n = 75;
printf("%d ", n);
solve(n, true);
printf("\n");
}
Output
75 / 25 / 5 - 4 / 2 - 1 - 0
Iterative
TBD
If you start looking for a divisor with 2, and work your way up, then the last pair of divisors you find will include the largest divisor. Alternatively you can start searching with divisor = N/2 and work down, when the first divisor found will have be largest divisor of N.
int minmoves(int n){
if(n<=3){
return n;
}
int[] dp=new int[n+1];
Arrays.fill(dp,-1);
dp[0]=0;
dp[1]=1;
dp[2]=2;
dp[3]=3;
int sqr;
for(int i=4;i<=n;i++){
sqr=(int)Math.sqrt(i);
int best=Integer.MAX_VALUE;
while(sqr >1){
if(i%sqr==0){
int fact=i/sqr;
best=Math.min(best,1+dp[fact]);
}
sqr--;
}
best=Math.min(best,1+dp[i-1]);
dp[i]=best;
}
return dp[n];
}
Well, I was looking on the net for a code to calculate the power of e (e^x) and found a few good codes for that. Then I found the following code and just wants to know what the n = 999 part and n <= 100 part are supposed to do? I mean.. why n <= 100? why n = 999?
#include<stdio.h>
#define ACCURACY 0.0001
int main() {
int n, count;
float x, term, sum;
printf("\nEnter value of x :");
scanf("%f", &x);
n = term = sum = count = 1;
while (n <= 100) {
term = term * x / n;
sum = sum + term;
count = count + 1;
if (term < ACCURACY)
n = 999;
else
n = n + 1;
}
printf("\nTerms = %d Sum = %f", count, sum);
return 0;
}
It's just a sum of terms in a series.
The term < ACCURACY test just looks to see if the desired accuracy was reached. If not, it goes to the next term in the series. If yes, n = 999 just makes the loop end. You could put there break; with the same result.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I try to print the prime numbers; 2 to 1 million. But nothing printed on the console. Could you check my code? And how can I be this code more optimized?
Here's my code:
#include <stdio.h>
#include <math.h>
main()
{
int num, sr, num2;
for (num = 2; num <= 1000000; num++) {
sr = (int) sqrt(num);
for (num2 = 2; sr % num2 != 0; num2++) {
if (sr == num2) {
printf("%d\n", sr);
}
}
}
}
Did it compile?
line 4: main() should be int main()?
another thing: sr = 1. 1 modulo any number is 1.
and finally. sr will never be equal to num2, because sr is 1 and num2 is 2 or greater so it will never print anything.
this will get you into an infinite loop that does nothing
If you wish to optimize it, you should use something like the sieve of eratosthenes.It is easy to operate on your data range. You can read more about it here :
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
#include <stdio.h>
#include <math.h>
int main(){
int num, sr, num2;
int isPrime = 1; // this is a check parameter; isPrime = 0 if number is not prime.
for(num=2; num<=100; num++){
sr = (int) sqrt(num);
for(num2=2; num2 <= sr; num2++){
//num2 <== sr to stop the innner loop
if(num%num2 == 0){
//printf("=========== %d|%d\n", num,num2); // uncomment this to see if a number is divisable
isPrime = 0; // this number is not prime, cos num can be divided by num2
break;
}
}
if(isPrime){
printf("Prime number is %d\n", num);
isPrime = 1; // reset the check parameter
}else{
isPrime = 1; // reset the check parameter
}
}
return 0;
}
This code works. Since it works, i'll let you play with it and optimize it. If you can't let us know. We'll try to help you.
I like how you used sqrt to optimize the code.
One optimization that you can use is the fact that all primes above 3 are of the form 6n+1 or 6n-1 and the fact that if a number is divisible by a prime, it is not a prime. Here is some code that uses that fact:
#include <stdio.h>
#include <math.h>
int is_prime(long num)
{
int k = 1, a = 0, b = 0;
long sr;
switch(num)
{
case 1: return 0;
case 2: return 1;
case 3: return 1;
case 4: return 0;
case 5: return 1;
case 6: return 0;
case 7: return 1;
}
if (num % 2 == 0) return 0;
if (num % 3 == 0) return 0;
sr = (int) sqrt(num);
while (b < sr) {
a = (6 * k) - 1;
b = (6 * k) + 1;
if (num % a == 0)
return 0;
if (num % b == 0)
return 0;
k += 1;
}
return 1;
}
void main(void)
{
int j;
for (j = 0; j<100; j++){
if (is_prime(j))
printf("%d is a prime\n", j);
}
}
This function returns 1 if num is a prime.
#include <stdlib.h>
#include <stdio.h>
int main (){
int n, cont, fib, na = 0, nb = 1, sum_even = 0;
printf ("Insert a number and I'll tell you the respective Fibonacci: ");
scanf ("%d", &n);
for (cont = 1; cont < n; cont++) {
na += nb;
nb = na - nb;
fib = na + nb;
if (fib % 2 == 0) {
sum_even += fib;
}
}
printf ("%d\n", sum_even);
return 0;
}
I was trying to do the Project Euler Problem 2, and then I came up with this code. The problem is: I can't find the sum of the pair numbers on fibonacci's sequence for numbers over 400 or something near that, because memory overflows. In consequence, I cant solve the exercise, since it asks to find the sum of the pair numbers below 4000000 in fibonacci's sequence. Can anyone help me?
Edit:
I tried to used float type numbers to increase the answer's capacity, it seems to work till a thousand or so, but if I try with bigger numbers, I get a -nan error in bash after like 15 secs of processing (I don't really know what it means).
#include <stdlib.h>
#include <stdio.h>
int main () {
int n, cont, div;
float sum_even = 0, na = 0, nb = 1, fib;
printf ("Insert a number and I'll tell you the respective Fibonacci: ");
scanf ("%d", &n);
for (cont = 1; cont <= n; cont++) {
na += nb;
nb = na - nb;
fib = na + nb;
div = fib / 2;
if (div % 2 == 0) {
sum_even += fib;
}
}
printf ("%f\n", sum_even);
return 0;
}
What you observe is not a memory overflow, it is a numeric overflow. The whole point of the exercise was to show that overflow does happen, and make you learn techniques to deal with it. In this particular case, they expect you to either implement arbitrary precision integer arithmetic, or borrow a pre-made implementation and use it with your solution.
You misunderstood the problem statement. The task is to find the sum of
{ fib(n) : fib(n) <= 4000000 && fib(n) % 2 == 0 }
and not
{ fib(n) : n <= 4000000 && fib(n) % 2 == 0 }
That task is solved without problems with a minor modification to your code. Instead of
for (cont = 1; cont < n; cont++) {
use
while(fib <= n) {