I am trying to code a Fibonacci generator, and so far I was able to calculate it and got accurate results, but I keep receiving trailing commas and I wanted to add a period(.) at the end of the result.
#include <stdio.h>
int f1=0,f2=1,i,sum=0,n,a;
printf("Please enter the number for Fibonacci numbers.\n");
scanf("%d",&n);
if(n==0){
printf("%d.",n);
}
else if(n==1){
a = n-1;
printf("%d, %d.",a,n);
}
else{
for(i=0;i<=n;i++){
printf("%d, ",f1);
sum = f1+f2;
f1 = f2;
f2 = sum;
}
}
return 0;
}
For example, n = 6
I wanted:
0, 1, 1, 2, 3, 5, 8.
What I got earlier:
0, 1, 1, 2, 3, 5, 8,
Fetching the idea from the comments:
// I'd prefer unsigned as negative numbers are meaningless anyway
unsigned int f1 = 0, f2 = 1;
unsigned int n = 7;
printf("0"); // 0 is printed in *any* case
while(--n) // or with for loop from 0 as long as < (not <= any more!)
// note the first value *is* printed already
{
printf(", %d", f2); // prepending the comma, one value is already there
// f2: now using the larger of the two,
// as the smaller *is* printed already
unsigned int sum = f1 + f2; // (limiting scope of to where it
// actually is needed)
f1 = f2;
f2 = sum;
}
puts(".");
Bonus: No special cases necessary any more...
Just start the loop with the second number :-)
else{ else{
printf("0"); // 0 here
for(i=0;i<=n;i++){ for(i=1;i<=n;i++){ // start at 1
printf("%d, ",f1); printf(", %d",f1); // change order
sum = f1+f2; sum = f1+f2;
f1 = f2; f1 = f2;
f2 = sum; f2 = sum;
} }
printf(".\n"); // add period
} }
If it was me, i'd keep the code simple, i wouldn't use negative indices, and i wouldn't start from position 1 instead of 0. What I would do is as follows:
#include <stdio.h>
int main(){
// Always initialise variables, integers cost nothing to initialise
// We use long because Fibonacci numbers can get quite large quite quickly.
long long int f1=0,f2=1,iterations=0;
printf("Please enter the number for Fibonacci numbers.\n");
if(scanf("%lld",&iterations)!=1){
// This means we've failed to read a number.
puts("Something is wrong with the input, exiting.");
return -1;
}
// ++iterations; // uncomment if you want iterations+1 Fibonacci numbers
for(long long int i=0;i<iterations;++i){
printf("%lld",f1);
int f3=f1+f2;
f1=f2;
f2=f3;
if(i<iterations-1){
printf(", ");
}
}
if(iterations>0){
puts(".");
}
return 0;
}
To compile and run:
martyn#Atlas:~$ gcc Deleteme.c
martyn#Atlas:~$ ./a.out
Please enter the number of Fibonacci numbers.
6
0, 1, 1, 2, 3, 5.
martyn#Atlas:~$
Note that your original program outputs 7 Fibonacci numbers, rather than 6. If you want 1 more than you input, then increment iterations before the loop, by doing something like ++iterations;
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int n = argc > 1 ? strtol(argv[1], NULL, 0) : 10;
int f[2] = {1,1};
while( n-- ) {
printf("%d%s", f[0], n ? ", " : ".\n");
int t = f[0] + f[1];
f[0] = f[1];
f[1] = t;
}
return 0;
}
Related
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
b=1;
a=0;
scanf("%d", &a);
while (a>0)
{
c=a%10;
if (c==0)
b=b*1;
else {
b=b*(a%10);
a=a/10;
}
}
printf("Proizvedenie: %d\n", b);
return 0;
}
It doesnt work when I add 0 in any position of number, but i added if and dont know why it doesnt work, cycle just does not end, pls help
01234 - 24; Right
1234 - 24; Right
12304 - doesnt work
12340 - doesnt work
WHY PLS HELP =(
You're only dividing a by 10 when the current digit is not 0. When the digit is 0 a stays the same and you and up in an infinite loop.
Move the update of a to outside of the if block. Also, b=b*1 is a no-op, so you can remove that.
while (a>0)
{
c=a%10;
if (c!=0) {
b=b*c;
}
a=a/10;
}
You're only doing a = a/10 in the else block. So when you get to a 0 digit, you stop dividing by 10 and get stuck in an infinite loop.
Take that line out of the if/then, since it needs to be done every time.
while (a>0)
{
c=a%10;
if (c!=0) {
b *= c;
}
a /= 10;
}
unsigned int product(int x)
{
int result = !!x;
while(x)
{
if(x % 10) result *= abs(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
int testData[] = {0, 1234, 12304, 12340, -1234, -12304, -012340 /* <- octal number!! */};
for(int x = 0; x < sizeof(testData)/sizeof(testData[0]); x ++)
printf("%d - %u\n", testData[x], product(testData[x]));
}
https://godbolt.org/z/T8T1a5YEE
Use functions.
integers can be negative as well
You need to handle zero too.
In your code:
c=a%10;
if (c==0)
b=b*1;
else {
b=b*(a%10);
a=a/10;
}
you need to move a = a / 10 outside the if as it is only executed when a % 10 is not zero. If it is, a does not change and you are in an infinitive loop
Others have noted the flaw in your code (location of a=a/10; inside else code block.
Here is a branchless way to achieve your objective. "Branching" (using an if() conditional) can make code run much slower when the processor's pipeline prediction turns out to be wrong. When processing millions (or billions) of data items, this may be a significant cost in time.
#include <stdio.h>
#include <stdlib.h>
int main() {
int a = 0, prod = 1;
if( scanf( "%d", &a ) != 1 ) {
fprintf( stderr, "scanf failed\n" );
return 1;
}
for( a = abs(a); a; a /= 10 ) {
int r = a%10;
prod *= r+(r==0); // branchless technique
}
printf( "Proizvedenie: %d\n", prod );
return 0;
}
54300012
Proizvedenie: 120
When the value of r is one of 1-9, r==0 has the value 0.
When the value of r is 0 and r==0 has the value 1.
So the 10 different rhs values can be 1, 1, 2, 3, 4, 5, 6, 7, 8 or 9.
#include<stdio.h>
int factorial(int a){
int b;
if (a==0)
return 1;
else
for (b=1;b<=a;b++)
a=a*b;
} //factorial of a
int pascal(int i, int j){
return (factorial(i))/((factorial(j))*factorial(i-j));
}
int main()
{
int k,n,m,q;
printf("Input m: ");
scanf("%d", &m);
for(k=0;k<m;k++){
for(n=0;n<=k;n++)
printf("%d ", pascal(k, n));
printf("\n");
}
}
I make a program that print the Pascal triangle but it make the right answer if height<=3, when I input m=6; it will print:
1
1 1
1 3 1
1 0 0 1
1 0 0 0 1
1 0 0 0 0 1
Can you help me find the bugs in my code?
that's because you have written the wrong logic in the function factorial().
for (b=1;b<=a;b++)
a=a*b;//also , you have to return the value of a here!
here, suppose a = 3, then, in 1st iteration, a = 3*1 equals 3, in 2nd iteration, a=3*2 equals 6; since 6>3 ,loop terminates and you got the right answer!!
but if a = 4, then, in 1st iteration, a = 4*1 equals 4, in 2nd iteration, a=4*2 equals 8 which is greater than 4, therefore loop does not executes further and you got the wrong answer!
the correct logic would be, to declare another int variable and initialize it to 1 to store the product of 'a' and the variable in it itself i.e,
int fac=1;
for(b=1;b<=a;b++){
fac = fac*b;
}
return fac;
so, the full code will be,
#include<stdio.h>
int factorial(int a){
int b=0;
if (a==0)
return 1;
else{
/* for(b=1;b<=a;b++){
fac = b*(factorial(b-1));// another way to find factorial using recursion
return fac;
}*/
int fac=1;
for(b=1;b<=a;b++){
fac = fac*b;
}
return fac;
}
} //factorial of a
int pascal(int i, int j){
return factorial(i) / (factorial(j) *factorial(i-j));
}
int main()
{
int k,n,m,q;
printf("Input m: ");
scanf("%d", &m);
for(k=0;k<m;k++){
for(n=0;n<=k;n++)
printf("%d ", pascal(k, n));
printf("\n");
}
return 0; // a good habit to add return 0, to let the compiler know that
// the code is executed completely
}
When I try to write a small program in C language that is intended to generate a 4-digit integer for which every digit is distinct and nonzero, the returned value is always in pattern like 1abc: the first digit seems to always be 1, and sometimes the returned value will be more than 4-digit like 56127254. Could anyone help me look into this? Thank you very much in advance.
So basically the program includes two functions, int isvalid(int n) and int choose_N(void).
isValid return 1 if the integer consists of exactly 4 decimal digits, and all these digits are nonzero and distinct, and 0 otherwise.
And int choose_N(void) generates an integer that is 4-digit and all the digits are distinct and nonzero.
Here is my code:
#define N_DIGITS 4
....
....//the main function
int isvalid(int n){
int i, x; int check[N_DIGITS]={0};
for(i=1;i<=N_DIGITS;i++){ //check whether all digits are nonzero
if((check[i-1]=n%10)==0){
return 0;
}
n /= 10;
}
for(i=0;i<N_DIGITS-1;i++){ // check whether all digits are distinct
for(x=i+1;x<N_DIGITS;x++){
if(check[i]==check[x])
return 0;
}
}
return 1;
}
int choose_N(void){
int i; int number=0;
while(!isvalid(number)){
for(i=0;i<N_DIGITS;i++){
srand(time(0));
number += ((10^i)*(rand()%10));
}
}
return number;
}
For srand(time(0));, I have tried various alternatives like srand(time(0)+i); or put this statement out of while loop, but those attempts seemingly did not work and still the returned value of choose_Nstill showed the werid pattern that I described.
your choose_N method has several issues:
First, if the number isn't valid, you're not resetting it to 0, so it just grows and grows.
Second, srand(time(0)) is not necessary within the loop (and could yield the same result for several iterations), just do it at program start (srand() — why call it only once?)
Third and biggest mistake: 10 ^ i is 10 xor i, not 10**i. You can use an aux value and multiply by 10 in your loop. Since number of digits is low, no risk of overflow
minor remark: you want to pass in the loop at least once, so use a do/while construct instead, so you don't have to force the first while test.
I'm trying to fix your code:
int choose_N(void){
int i, number;
do
{
number = 0;
int p = 1;
for(i=0;i<N_DIGITS;i++)
{
number += p*(rand()%10);
p *= 10;
}
} while(!isvalid(number));
return number;
}
While #Jean-François-Fabre answer is the right one, it is not optimal algorithm. Optimal algorithm in such case would be using FIsher-Yates-Knuth shuffle and Durstenfeld's implementation.
Shuffling right array will produce numbers which are automatically valid, basically no need for isvalid(n) anymore.
Code
// Swap selected by index digit and last one. Return last one
int
swap_array(int digits[], int idx, int last) {
if (idx != last) { // do actual swap
int tmp = digits[last];
digits[last] = digits[idx];
digits[idx] = tmp;
}
return digits[last];
}
int
choose_N_Fisher_Yates_Knuth() {
int digits[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int r = 0;
for (int k = 0; k != N_DIGITS; ++k) {
int idx = rand() % (9 - k);
int n = swap_array(digits, idx, (9 - k) - 1);
r = r * 10 + n;
}
return r;
}
int
main() {
srand(12345);
int r, v;
r = choose_N_Fisher_Yates_Knuth();
v = isvalid(r);
printf("%d %d\n", r, v);
r = choose_N_Fisher_Yates_Knuth();
v = isvalid(r);
printf("%d %d\n", r, v);
r = choose_N_Fisher_Yates_Knuth();
v = isvalid(r);
printf("%d %d\n", r, v);
r = choose_N_Fisher_Yates_Knuth();
v = isvalid(r);
printf("%d %d\n", r, v);
return 0;
}
Output
7514 1
6932 1
3518 1
5917 1
I'm trying to write a program that will print the factorial of a given number in the form:
10!=2^8 * 3^4 * 5^2 * 7
To make it quick lets say the given number is 10 and we have the prime numbers beforehand. I don't want to calculate the factorial first. Because if the given number is larger, it will eventually go beyond the the range for int type. So the algorithm i follow is:
First compute two’s power. There are five numbers between one and ten that two divides into. These numbers are given 2*1, 2*2, …, 2*5. Further, two also divides two numbers in the set {1,2,3,4,5}. These numbers are 2*1 and 2*2. Continuing in this pattern, there is one number between one and two that two divides into. Then a=5+2+1=8.
Now look at finding three’s power. There are three numbers from one to ten that three divides into, and then one number between one and three that three divides into. Thus b=3+1=4. In a similar fashion c=2. Then the set R={8,4,2,1}. The final answer is:
10!=2^8*3^4*5^2*7
So what i wrote is:
#include <stdio.h>
main()
{
int i, n, count;
int ara[]={2, 3, 5, 7};
for(i=0; i<4; i++)
{
count=0;
for(n=10; n>0; n--)
{
while(n%ara[i]==0)
{
count++;
n=n/ara[i];
}
}
printf("(%d^%d)" , ara[i], count);
}
return 0;
}
and the output is (2^3) (3^2) (5^1) (7^1).
I can't understand what's wrong with my code. Can anyone help me, please?
Much simpler approach:
#include <stdio.h>
int main(int argc, char const *argv[])
{
const int n = 10;
const int primes[] = {2,3,5,7};
for(int i = 0; i < 4; i++){
int cur = primes[i];
int total = 0;
while(cur <= n){
total += (n/cur);
cur = cur*primes[i];
}
printf("(%d^%d)\n", primes[i], total);
}
return 0;
}
Your code divides n when it is divisible for some prime number, making the n jumps.
e.g. when n = 10 and i = 0, you get into while loop, n is divisible by 2 (arr[0]), resulting in n = 5. So you skipped n = [9..5)
What you should do is you should use temp when dividing, as follows:
#include <stdio.h>
main()
{
int i, n, count;
int ara[]={2, 3, 5, 7};
for(i=0; i<4; i++)
{
count=0;
for(n=10; n>0; n--)
{
int temp = n;
while(temp%ara[i]==0)
{
count++;
temp=temp/ara[i];
}
}
printf("(%d^%d)" , ara[i], count);
}
return 0;
}
For finding factorial of a no pl. try this code:
#include <stdio.h>
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}
i am doing one of the simple programin C, sum of digits of 5 digit number.Though i had done it using a simple function but i need to do it with recursion also.I had read many solution on net regarding this problem using recursion and had implemented one of mine.But that is giving error and i cant figure out what mesh i am doing in my algo.
#include<stdio.h>
int sum5(int x); //function for sum of digits of 5 digit number
int main()
{
int x;
int result;
printf("Enter a 5 digit number : ");
scanf("%d",&x);
printf("Number entered by you is %d",x);
result = sum5(x);
printf("Sum of digits of 5 digit number is = %d",&result);
return 0;
}
int sum5(int x)
{
int r;
int sum=0;
if(x!=0){
r=x%10;
sum=sum+r;
x=x-r; //doing this so that 0 come in the last and on diving it by 10, one digit will be removed.
sum5(x/10);
}
return sum;
}
but after its execution i am getting wrong result.It is dumping some anonymous value on the output.
Also, your sum5 function is incorrect. You have to add the value of sum5 to the sum variable of the caller function.
int sum5(int x)
{
int r;
int sum = 0;
if (x != 0) {
r = x % 10;
sum = r;
//x = x - r; - this isn't required. integer division will floor x
sum += sum5(x / 10);
}
return sum;
}
This is incorrect as it is printing the address of result and not its value:
printf("Sum of digits of 5 digit number is = %d",&result);
Change to:
printf("Sum of digits of 5 digit number is = %d", result);
Always check the result of scanf() to ensure a valid value was read:
/* Returns number of assignments made. */
if (scanf("%d", &x) == 1 && x > 9999 && x < 100000)
{
}
Plus the error in the implementation of sum5() as pointed out by Osiris
.