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.
Related
I am solving an exercise in C and I got stuck. I don't know the logic of the code to get to my solution. For example we enter 2 numbers from input let the numbers be 123451289 and 12 and I want to see how many times number 2 is showing at number 1 (if this is confusing let me know). For the numbers earlier the program outputs 2. I tried solving it here is my code:
#include <stdio.h>
int main() {
int num1, num2, counter = 0;
scanf("%d%d", num1, num2);
if (num1 < num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
int copy1 = num1;
int copy2 = num2;
while (copy2 > 0) {
counter++; // GETTING THE LENGHT OF THE SECOND NUMBER
copy2 /= 10;
// lastdigits = copy1 % counter //HERE I WANT TO GET THE LAST DIGITS OF THE FIRST NUMBER
// But it does not work
}
}
My question is how can I get the last digits of the first number according to the second one for example if the second number have 3 digits I want to get the last 3 digits of the first number. For the other part I think I can figure it out.
I must solve this problem WITHOUT USING ARRAYS.
The problem: find all the needles (e.g. 12) in a haystack (e.g. 123451289).
This can be done simply without arrays using a modulus of the needle. For 12, this is 100. That is, 12 is two digits wide. Using the modulus, we can
isolate the rightmost N digits of the haystack and compare them against the needle.
We "scan" haystack repeatedly by dividing by 10 until we reach zero.
Here is the code:
#include <stdio.h>
int
main(void)
{
int need, hay, counter = 0;
scanf(" %d %d", &hay, &need);
// ensure that the numbers are _not_ reversed
if (hay < need) {
int temp = need;
need = hay;
hay = temp;
}
// get modulus for needle (similar to number of digits)
int mod = 1;
for (int copy = need; copy != 0; copy /= 10)
mod *= 10;
// search haystack for occurences of needle
// examine the rightmost "mod" digits of haystack and check for match
// reduce haystack digit by digit
for (int copy = hay; copy != 0; copy /= 10) {
if ((copy % mod) == need)
++counter;
}
printf("%d appears in %d exactly %d times\n",need,hay,counter);
return 0;
}
UPDATE:
I'm afraid this does not work for 10 0. â
chqrlie
A one line fix for to the modulus calculation for the 10/0 case. But, I've had to add a special case for the 0/0 input.
Also, I've added a fix for negative numbers and allowed multiple lines of input:
#include <stdio.h>
int
main(void)
{
int need, hay, counter;
while (scanf(" %d %d", &hay, &need) == 2) {
counter = 0;
// we can scan for -12 in -1237812
if (hay < 0)
hay = -hay;
if (need < 0)
need = -need;
// ensure that the numbers are _not_ reversed
if (hay < need) {
int temp = need;
need = hay;
hay = temp;
}
// get modulus for needle (similar to number of digits)
int mod = need ? 1 : 10;
for (int copy = need; copy != 0; copy /= 10)
mod *= 10;
// search haystack for occurences of needle
// examine the rightmost "mod" digits of haystack and check for match
// reduce haystack digit by digit
for (int copy = hay; copy != 0; copy /= 10) {
if ((copy % mod) == need)
++counter;
}
// special case for 0/0 [yecch]
if ((hay == 0) && (need == 0))
counter = 1;
printf("%d appears in %d exactly %d times\n", need, hay, counter);
}
return 0;
}
Here is the program output:
12 appears in 123451289 exactly 2 times
0 appears in 10 exactly 1 times
0 appears in 0 exactly 1 times
UPDATE #2:
Good fixes, including tests for negative numbers... but I'm afraid large numbers still pose a problem, such as 2000000000 2000000000 and -2147483648 8 â
chqrlie
Since OP has already posted an answer, this is bit like beating a dead horse, but I'll take one last attempt.
I've changed from calculating a modulus of needle into calculating the number of digits in needle. This is similar to the approach of some of the other answers.
Then, the comparison is now done digit by digit from the right.
I've also switched to unsigned and allow for the number to be __int128 if desired/supported with a compile option.
I've added functions to decode and print numbers so it works even without libc support for 128 bit numbers.
I may be ignoring [yet] another edge case, but this is an academic problem (e.g. we can't use arrays) and my solution is to just use larger types for the numbers. If we could use arrays, we'd keep things as strings and this would be similar to using strstr.
Anyway, here's the code:
#include <stdio.h>
#ifndef NUM
#define NUM long long
#endif
typedef unsigned NUM num_t;
FILE *xfin;
int
numget(num_t *ret)
{
int chr;
num_t acc = 0;
int found = 0;
while (1) {
chr = fgetc(xfin);
if (chr == EOF)
break;
if ((chr == '\n') || (chr == ' ')) {
if (found)
break;
}
if ((chr >= '0') && (chr <= '9')) {
found = 1;
acc *= 10;
chr -= '0';
acc += chr;
}
}
*ret = acc;
return found;
}
#define STRMAX 16
#define STRLEN 100
const char *
numprt(num_t val)
{
static char strbuf[STRMAX][STRLEN];
static int stridx = 0;
int dig;
char *buf;
buf = strbuf[stridx++];
stridx %= STRMAX;
char *rhs = buf;
do {
if (val == 0) {
*rhs++ = '0';
break;
}
for (; val != 0; val /= 10, ++rhs) {
dig = val % 10;
*rhs = dig + '0';
}
} while (0);
*rhs = 0;
if (rhs > buf)
--rhs;
for (char *lhs = buf; lhs < rhs; ++lhs, --rhs) {
char tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}
return buf;
}
int
main(int argc,char **argv)
{
num_t need, hay, counter;
--argc;
++argv;
if (argc > 0)
xfin = fopen(*argv,"r");
else
xfin = stdin;
while (1) {
if (! numget(&hay))
break;
if (! numget(&need))
break;
counter = 0;
// we can scan for -12 in -1237812
if (hay < 0)
hay = -hay;
if (need < 0)
need = -need;
// ensure that the numbers are _not_ reversed
if (hay < need) {
num_t temp = need;
need = hay;
hay = temp;
}
// get number of digits in needle (zero has one digit)
int ndig = 0;
for (num_t copy = need; copy != 0; copy /= 10)
ndig += 1;
if (ndig == 0)
ndig = 1;
// search haystack for occurences of needle
// starting from the right compare digit-by-digit
// "shift" haystack right on each iteration
num_t hay2 = hay;
for (; hay2 != 0; hay2 /= 10) {
num_t hcopy = hay2;
// do the rightmost ndig digits match in both numbers?
int idig = ndig;
int match = 0;
for (num_t need2 = need; idig != 0;
--idig, need2 /= 10, hcopy /= 10) {
// get single current digits from each number
int hdig = hcopy % 10;
int ndig = need2 % 10;
// do they match
match = (hdig == ndig);
if (! match)
break;
}
counter += match;
}
// special case for 0/0 et. al. [yecch]
if (hay == need)
counter = 1;
printf("%s appears in %s exactly %s times\n",
numprt(need), numprt(hay), numprt(counter));
}
return 0;
}
Here's the program output:
12 appears in 123451289 exactly 2 times
123 appears in 123451289 exactly 1 times
1234 appears in 123451289 exactly 1 times
1 appears in 123451289 exactly 2 times
0 appears in 10 exactly 1 times
0 appears in 0 exactly 1 times
1000000000 appears in 1000000000 exactly 1 times
2000000000 appears in 2000000000 exactly 1 times
This looks along the lines of what you're attempting.
You can use the pow() function from math.h to raise 10 to the power of how many digits you need for your modulus operation.
Compile with -lm or make your own function to calculate 10^num_digits
#include <stdio.h>
#include <math.h>
int main() {
int x = 123456789;
double num_digits = 3.0;
int last_digits = x % (int)pow(10.0, num_digits);
printf("x = %d\nLast %d Digits of x = %d\n", x, (int)num_digits, last_digits);
return 0;
}
Outputs:
x = 123456789
Last 3 Digits of x = 789
I think you are trying to ask :- if number1 = 1234567 and number2 = 673, then, length of number2 or number2 has 3 digits, so, you now want the last 3 digits in number1, i.e, '456', if I'm not wrong.
If that is the case, then, what you did to find the number of digits in num2 is correct, i.e,
while (copy2>0) {
counter++; // GETTING THE LENGHT OF THE SECOND NUMBER
copy2/=10;
}
you can do the same for number1 and find out its number of digits, then you can compare whether the number of digits in number2 is less than that in number1. Ex, 3 is less than number of digits in number1, so you can proceed further. Let's say number of digits in number1 is 7 and you want the last 3 digits, so you can do iterate over the digits in number1 till count of digits in number2 and pop out each last digit and store them in an array.
The code:
#include <stdio.h>
int main()
{
int num1,num2;
int count1 = 0, count2 = 0;
scanf("%d",&num1);
scanf("%d",&num2);
if(num1<num2){
int temp = num1;
num1 = num2;
num2 = temp;
}
int copy1 = num1;
int copy2 = num2;
while (copy1>0)
{
count1++;
copy1/=10;
}
while (copy2>0)
{
count2++;
copy2/=10;
}
// printf("num1 has %d digits and num2 has %d digits\n", count1, count2);
if (count1 >= count2)
{
int arr[count2];
int x = count2;
int p = num1;
int i = 0;
while (x > 0)
{
arr[i++] = p%10;
x --;
p/=10;
}
for (int j = 0; j < i; j++)
{
printf("%d ", arr[j]);
}
}
return 0;
}
output : 8 7 6
let's say, num1 = 12345678, num2 = 158, then arr = {8,7,6}.
You must determine the number of digits N of num2 and test if num1 ends with num2 modulo 10N.
Note these tricky issues:
you should not sort num1 and num2: If num2 is greater than num1, the count is obviously 0.
num2 has at least 1 digit even if it is 0.
if num1 and num2 are both 0, the count is 1.
if num2 is greater then INT_MAX / 10, the computation for mod would overflow, but there can only be one match, if num1 == num2.
it is unclear whether the count for 1111 11 should be 2 or 3. We will consider all matches, including overlapping ones.
to handle larger numbers, we shall use unsigned long long instead of int type.
Here is a modified version:
#include <limits.h>
#include <stdio.h>
int main() {
int counter = 0;
unsigned long long num1, num2;
if (scanf("%llu%llu", &num1, &num2) != 2) {
printf("invalid input\n");
return 1;
}
if (num1 == num2) {
/* special case for "0 0" */
counter = 1;
} else
if (num1 > num2 && num2 <= ULLONG_MAX / 10) {
unsigned long long copy1 = num1;
unsigned long long mod = 10;
while (mod < num2) {
mod *= 10;
}
while (copy1 > 0) {
if (copy1 % mod == num2)
counter++;
copy1 /= 10;
}
}
printf("count=%d\n", counter);
return 0;
}
Note that leading zeroes are not supported in either number: 101 01 should produce a count of 1 but after conversion by scanf(), the numbers are 101 and 1 leading to a count of 2. It is non trivial to handle leading zeroes as well as numbers larger than ULLONG_MAX without arrays.
This was the answer that i was looking for but thank you all for helping :)
#include <stdio.h>
#include <math.h>
int main(){
int num1,counter1,counter2,num2,temp,digit,copy1,copy2;
scanf("%d%d",&num1,&num2);
if(num1<num2){
temp = num1;
num1 = num2;
num2 = temp;
}
copy1 = num1;
copy2 = num2;
counter1 = counter2 = 0;
while (copy2>0) {
counter1++;
copy2/=10;
}
counter1 = pow(10,counter1);
if(num1> 1 && num2>1)
while (copy1>0) {
digit = copy1%counter1;
if(digit==num2){
counter2++;
}
copy1/=10;
} else{
if(num2<1){
while (copy1>0) {
digit = copy1%10;
if(digit==copy2){
counter2++;
}
copy1/=10;
}
}
}
printf("%d",counter2);
}
I'm a first year student in a programming university and my first assignment is to find the sum of prime numbers between 3990000000 and 4010000000. The problem is everything I do, when I run the program it says the sum is 0 with a return value of 25. I've been trying to debug this code but with no luck, could someone help me?
My code is:
#include <stdio.h>
#define STARTNUMBER 3990000000
#define ENDNUMBER 4010000000
int main() {
unsigned int num;
int j, c, flag, sum = 0;
flag = 1;
c = 5;
j = 7;
for (num = STARTNUMBER; num <= ENDNUMBER; num++) {
if (num % 2 == 0) { /*if number mod 2 equals zero go to next number*/
flag = 0;
break;
}
if (num % 3 == 0) { /*if number mod 3 equals zero go to next number*/
flag = 0;
break;
} else
/*check if number is prime with the sequences 5+6+6...<=sqrt(number) and 7+6+6..<=sqrt(number)*/
while (c * c <= num && j * j <= num && flag == 1) {
if (num % c == 0 || num % j == 0) {
flag = 0;
break;
}
c += 6;
j += 6;
}
if (flag == 1)
sum++;
}
printf("There are %d prime numbers", sum);
}
You are asking for the sum of the prime number, even if your code is just printing how many they are. Assuming you've misunderstood the exercise, I try to show a possible problem of your original question, glimpsing a possible trick in your exercise since the interval is very close to 232.
Assuming also you are on a 64-bit environment, if there are at least two prime numbers in that inteval, the sum is going to be greater than INT_MAX (231 - 1). An int is not sufficient to store a value, and also unsigned int is not sufficient since UINT_MAX is 232 - 1.
Finally, assuming you've solved your problems with the break statements already described in the comments, try to store your sum variable into a unsigned long int, and replace the last part of the loop with
if (flag==1)
sum += num;
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
The programs below calculate the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. Which one would you choose between the two and why?
1st piece of code:
#include <stdio.h>
#define ulong unsigned long
int main(void)
{
const ulong val = 20;
ulong x;
ulong y;
for (x = val; ; x += val)
{
for (y = val - 1; y; y--)
{
if (x % y != 0)
{
break;
}
}
if (y == 0)
{
printf("Answer = %u \n", x);
break;
}
}
return 0;
}
2nd piece of code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
bool isDivisable(int x);
int main()
{
int a = 20;
while (true)
{
a+=20;
if (isDivisable(a))
{
break;
}
}
printf("%d\n", a);
system("pause");
return 0;
}
bool isDivisable(int x)
{
for (int i = 11; i < 21; i++)
{
if (x%i != 0)return false;
}
return true;
}
Also, what does this for loop stand for?:
for (y = val - 1; y; y--)
It iterates until it reaches what exactly? Would the code (y = val - 1; ; y--) produce the same result?
The number you are trying to find is a least common multiple (LCM) of all numbers from 1 to 20. The LCM in this case will be equal to the product of multiplying the highest power of each prime divisor among numbers' prime factorization.
So, the result will be equal to 2^4 * 3^2 * 5 * 7 * 11 * 13 * 17 * 19 = 232792560
If you want to find LCM of all numbers from 1 to N, you can simply use sieve of Eratosthenes to find all prime numbers from 1 to N or choose any more optimized algorithm. Example in C (first peace of code rewritten):
#define ulong unsigned long
int main(void)
{
const ulong val = 20;
int isNotPrime[val+1];
memset(isNotPrime, 0, sizeof(isNotPrime));
isNotPrime[0] = isNotPrime[1] = 1;
ulong res = 1;
for (ulong i = 2; i <= val; ++i) {
if (!isNotPrime[i]) {
res *= pow(i, (int) (log(val) / log(i)));
}
for (ulong j = i*i; j <= val; j += i) {
isNotPrime[j] = 1;
}
}
printf("Answer = %lu \n", res);
return 0;
}
This might be something else to take into account:
// The least common multiple of numbers from 1 to 20.
// 2^4 * 3^2 * 5 * 7 * 11 * 13 * 17 * 19 = 232792560
// See also https://oeis.org/A003418 for details.
int lcm1_20() {
return 232792560
}
If you are only interested in the respective value (and you do not intend to change the parameter "20"), then using the pre-computed value, and an explanatory comment might be good enough.
Among the two codes you provided, I would choose the first one, mostly because of the following aspects which make the second version look not very professional:
the 2nd code doesn't consistently use white-spaces, e.g. a+=20, vs int a = 20;; also if (x%i != 0)return false; -- I think a white-space before the return looks better;
the method name, isDivisable contains a typo.
The loop 'for (y = val - 1; y; y--)' will loop as long at y is not 0. Your other example will never exit.
I'd prefer the first algorithm you proposed, since it eliminates an unnecessary function call, and is easier to read and understand.
Hello Guys I am trying to solve one problem given on the Hacker Rank. Though the problem is quite simple, I was thinking to solve the problem using some other concepts.
The problem is
Desription
You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our answer is 2.
Input Format
The first line contains T (the number of test cases), followed by T lines (each containing an integer N).
Constraints
1â¤Tâ¤15
0
I solved the problem earlier by defining variable N as of type long long but that i guess will not be the efficient way to solve the problem.
So i thought why not declare the variable N as an character array. This way we can also use the program to store the number greater then the max limit of long long also rt?
Say i used the following code
#include <stdio.h>
#include <string.h>
int main()
{
int i,t;
char n[20];
scanf("%d",&t);
while(t--)
{
scanf("%s",n);
int len=strlen(n);
int f2,f3,f5,f7,f4,count;
f2=f3=f5=f7=f4=count=0;
for( i=0;i<len;++i)
{ int sum=0;
switch((int)n[i])
{
case 48: break;
case 49: ++count;break;
case 50: if((int)n[len-1]%2==0) // divisibility by 2
{
++count;f2=1;
}break;
case 51: for(i=0;n[i]!='\0';++i) // divisibility by 3
{
sum+=(int)n[i];
}
if(sum%3==0)
{
++count;
f3=1;
}break;
case 52: if(f2==1) // divisibility by 4
{
++count;
f4=1;
} break;
case 53: if(n[len-1]=='5' || n[len-1]=='0') // divisibility by 5
{
++count;
f5=1;
}break;
case 54: if(f2==1 && f3==1) // divisibility by 6
{
++count;
break;
}
case 55: // Code for divisibilty by 7
case 56: if(f2==1 && f4==1) // divisibility by 8
{ ++count;
break;
}
case 57: if(f3==1) // divisibility by 9
{
++count;
break;
}
}
}
printf("%d\n",count);
}
return 0;
}
The program is working fine but the only problem is I am not able to rt the code for divisibility by 7 anu suggestions will be helpful, And also which is the better way to solve the problem , This way in which the variable N is declared as the character array or by declaring the variable N as long long.
Any improvements for the above code would also be appreciated .....:)
Divisibility by 7 can be checked by this rule
Also you can use this mod() function to check divisibility by any number :
int mod(char *n, int val)
{
int sum = 0;
for(int i=0; n[i]; i++)
{
sum = sum*10 + (n[i]-'0');
if(sum >= val)
sum = sum % val;
}
return sum;
}
it will return 0, if the number n is divisible by number val :)
And you don't need to check for every redundant digit.
First check the available digit then check for divisibility once for each digit.
Here's what you can do -
#include <stdio.h>
#include <string.h>
int mod(char *n, int val)
{
int sum = 0;
for(int i=0; n[i]; i++)
{
sum = sum*10 + (n[i]-'0');
if(sum >= val)
sum = sum % val;
}
return sum;
}
int main()
{
int i,t;
int digit[10];
char n[20];
scanf("%d",&t);
while(t--)
{
scanf("%s",n);
int len=strlen(n);
int cnt=0;
memset(digit,0,sizeof(digit)); // setting all the digit to 0
for(i=0;i<len;i++)
digit[n[i]-'0']++;
for(i=1;i<10;i++)
{
if(digit[i]==0) // number doesn't contain any of this digit
continue;
if(mod(n,i)==0)
cnt+=digit[i]; // Adding the digit to the answer
}
printf("%d\n",cnt);
}
return 0;
}
How this works :
for n = 147 and val = 7
sum = 0
1st iter >> sum = 0*10 + 1 = 1
sum < val, so continue
2nd iter >> sum = 1*10 + 4 = 14
sum >= val, so sum = sum % val = 14 % 7 = 0
3rd iter >> sum = 0*10 + 7 = 7
sum >= val, so sum = sum % val = 7 % 7 = 0
as the final sum is 0, so we can say that n is divisible by val :)
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$