Scanf error in C - c

So i have the following C code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int L,R;
scanf("%d",&L);
scanf("%d",&R);
long long int *a=malloc(L*sizeof(long long int*));
long long int *A=malloc(L*sizeof(long long int*));
int i;
for(i=0;i<L;i++)
scanf("%lld %lld",&a[i],&A[i]);
for(i=0;i<L;i++)
{
printf("a(%d)==%lld and A(%d)==%lld\n",i,a[i],i,A[i]);
}
return 0;
}
which is unfortunately only a starter of my problem, and with the print loop on the end i want to determine if the input values are assigned correctly into the arrays a and A
( the R value has to do with another two arrays b and B but for now this doesn't matter).
when i compile and run the program with these inputs:
3 5
10 1 3 2 10 1
i get on the output:
a(0)==10 and A(0)==10
a(1)==3 and A(1)==2
a(2)==10 and A(2)==1
Notice that everything puts up correctly, but the value A(0)=10 which instead of calculated to 1 , scanf reads for a second time the value 10, skips the value 1 and proceeds reading the rest of the values correctly. I'm really stuck. Does anyone have an idea why this incident occurs?

there is a mistake in the following line:
long long int *a=malloc(L*sizeof(long long int*));
you need to use sizeof(long long int) and not sizeof(long long int*)
Hope this helps to mitigate your issues.

Actually, the best way to do it is like this:
long long int *a = malloc(L * sizeof(*a));
That way if you change the type you only have to change it in one place.

Related

Runtime error in my code

I was trying to implement this problem from SPOJ: http://www.spoj.com/problems/COINS/ using memoization but I keep getting Runtime error and cant figure out why. Here is my code:
#include<stdio.h>
long long int max(long long int a,long long int b)
{
if(a >= b)
return a;
else
return b;
}
long long int dp[100000];
long long solve(long long int n)
{
long long ans;
if(n<=50000)
return dp[n];
else
ans=(n,solve(n/2)+solve(n/3)+solve(n/4));
return ans;
}
int main()
{
long long int n;
int t;
for(int i = 0;i <=50000;i++)
{
dp[i] = max(i,dp[i/2] + dp[i/3] + dp[i/4]);
}
while((scanf("%d",&t))>0)
printf("%lld",solve(n));
return 0;
}
Here are a few problems:
In solve, you have ans = (n,solve(n/2)...); The leading n has no effect. Did you intend this to be an argument list to max? If so, you need to add max. Otherwise it's just a comma expression and you might as well remove the leading n.
In main, your initialization of dp has a problem. Consider the first pass through the loop, when i is 0. In this case, i/2 etc. will also be zero, hence those dp values will be undefined. Try setting dp[0] explicitly, outside of the loop, and then start your loop at index 1 instead.
When printing the solution in main, you probably want to add newling \n to the end of your printf format string.
As noted by others, when calling solve from main, you are passing n rather than t.
The problem is most likely due to this:
while((scanf("%d",&t))>0)
printf("%lld",solve(n));
You are reading t but passing n which is uninitialized. You probably want to pass t to solve():
while((scanf("%d",&t))>0)
printf("%lld",solve(t));
Reason you get Runtime Error
while((scanf("%d",&t))>0)
printf("%lld",solve(n));
Here, You get input in variable t but pass variable n to solve function. Use variable t or n for both case. It will solve your problem.

Hacker Rank : Project Euler#1

I am new to competitive programming and I did a problem on Hacker Rank. The question statement is as follows:
"If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.
Input Format
First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N.
Output Format
For each test case, print an integer that denotes the sum of all the multiples of 3 or 5 below N."
Constraints
1≤T≤10^5
1≤N≤10^9
I've written the following code which successfully satisfies 3 test cases and fails at remaining two.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int func(int p,int n)
{
int j;
n=n-1;
j=n/p;
return (p*j*(j+1))/2;
}
int main()
{
unsigned long int n;
int t,j,count;
scanf("%d",&t);
if(t>=1 && t<=100000){
for(j=0;j<t;j++)
{
scanf("%lu",&n);
if(n>=1 && n<=1000000000)
{
count=func(3,n)+func(5,n)-func(15,n);
printf("%d\n",count);
}
}}
return 0;
}
What is the mistake in my code. Why isn't it getting accepted?
There are a couple of issues.
You are indeed overflowing your int when returning from func. Also, your printf statement should be printf("%llu\n", count);
So, the return from func, count, and the local variable j, should all be unsigned long long and your print out should reflect that as well. You need to make j unsigned long long because of the arithmetic in the return statement for func(this is at least the case in VS 2013).

why < is much faster than !=?

Problem : Consider the following algorithm to generate a sequence of
numbers. Start with an integer n. If n is even, divide by 2. If n is
odd, multiply by 3 and add 1. Repeat this process with the new value
of n, terminating when n = 1. The input will consist of a series of
pairs of integers i and j, one pair of integers perline. All integers
will be less than 1,000,000 and greater than 0.
For each pair of
input integers i and j, output i, j in the same order in which they
appeared in the input and then the maximum cycle length for integers
between and including i and j. These three numbers should be separated
by one space, with all three numbers on one line and with one line of
output for each line of input.
sample input :
1 10
sample output:
1 10 20
so i wrote this :
#include <stdio.h>
#include <string.h>
struct line{int in1;int in2;int result;};
int cycle(int in);
int main(int argc, char *argv[]) {
int cycle(int in);
char c;
int firstIn=0;
struct line l[500] ;
int pointer=0;
while(2<3){
l[pointer].in1=0;
l[pointer].in2=0;
scanf("%u %u",&l[pointer].in1,&l[pointer].in2);
if(l[pointer].in1<1||l[pointer].in2<1){
break;
}
int maxCyc=0;
int j,m;
int min,max;
if(l[pointer].in1>l[pointer].in2){
max=l[pointer].in1;
min=l[pointer].in2;
}
else{
max=l[pointer].in2;
min=l[pointer].in1;
}
for(j=min;j<=max;j++){
m = cycle(j);
if(m>maxCyc)
maxCyc=m;
}
l[pointer].result=maxCyc;
printf("%d %d %d\n",l[pointer].in1,l[pointer].in2,l[pointer].result);
pointer++;
}
}
int cycle(int in){
int cyc = 1;
while(in>1){
if(in%2==0){
cyc++;
in=in/2;
}
else{
cyc++;
in=in*3+1;
}
}
return cyc;
}
Its completly ok but when you change while(in>1) in cycle method to while(in!=1) it gets much more slower. my question is why?!
Time when its while(in>1) : 0.683 sec
and when its while(in!=1) : I waited more than 5 min nothing
happened yet :)
for input : 1 1000000
there is no infinite loop or something because in cant get below 1 at all(for that it must be already 1) .
Best regards
When you call cycle with the input value 113383, the process eventually sets n to
827370449, and 3*827370449+1 is 2482111348, which is greater than the maximum signed int and is interpreted as -1812855948. So there's your first negative number where there should be no negative number.
If this process then eventually sets n to -2, it will loop infinitely between -2 and -1 from then on. There may be other loops I haven't considered.
If you were to use an unsigned int, there is a possibility (I haven't checked) that this too will overflow eventually, which will not result in a negative value but will result in an incorrect value, invalidating your results.
No matter what integer representation you use, it would probably be a good idea to compare n with (maximum-1)/3 at the top of each loop, where maximum is the largest possible positive value of your integer type, just to be sure you do not overflow.
As you told me it was a simple overflow problem thx everyone.
max int value is 2,147,483,647; So when i changed int cycle(int in) to int cycle(long long int in) my problem was solved.
i also figured it out that my first answer with while(in>1) was wrong.
When an integer overflow occurs,the value will go below 0 .That was the reason while(in!=1) was an infinte loop.
I was really tired that i didn't figure it out by myself. sorry for that :)

a strange thing when test unsigned int value

today,I write some code to test unsigned int.
#include <stdio.h>
int sum_element(float ele[], unsigned int len);
int main(void){
float ele[] = {1.1,2.2,3.3};
float sum = sum_element(ele,3);
printf("sum is %f\n",sum);
return 0;
}
int sum_element(float ele[], unsigned int len){
int sum=0.0; //mistake,should be : float sum = 0.0
int i=0;
for(i=0;i<= len-1;i++){
printf("sum=%f, i=%d\n",sum,i);
sum += ele[i];
}
return sum;
}
in this example, i have a mistake, the type of variable sum, should be float, but i write int, the compile command:
gcc test.c -o test
and i run this code
./test
the output of the function sum_element is:
sum=0.000000, i=1
sum=0.000000, i=1
sum=0.000000, i=1
and then i found the mistakes, and i change the type of sum to float, then compiled again,
and when i run it, the output is :
sum=0.000000, i=0
sum=1.100000, i=1
sum=3.300000, i=2
this time, the output like normal,but in first output, why the variable of i is always the same value of 1, can someone tell me?
Nothing to see. You invoked undefined behavior by passing the wrong type to printf, so all output of the program is meaningless. The %f format specifier requires an argument of type double (by the way, float would automatically promote to double in this context, so float would be okay too), but you passed it an argument of type int.
You have to understand how va_arg work. Printf is a function that take a undefined number of arguments. The problem is that those arguments are not typed.
When you specify int, double, ect... the compiler assign differente number of bytes (in a specific order) depending on the arguments. So when you call a function that has type argument, the function know how it should read those bytes.
Here it cannot know since it isn't type. So the printf function is going to believe what you give it. If you ask for example for a 4 bytes when you real value is 8 bytes, the function will read the first 4 bytes believing it the value you ask for. But then the next value you try to match will start with the next 4 bytes. Wich will give you garbage.
You can try to do 2 printf, and you will see that the value of i is actually the good one. Only the way to read it was wrong.
int sum_element(float ele[], unsigned int len){
int sum=0.0; //mistake,should be : float sum = 0.0
int i=0;
for(i=0;i<= len-1;i++){
printf("sum=%f\n",sum);
printf("i=%d\n",i);
}
return sum;
}
Hope this can help.
EDIT:
Maybe a example is easier to understand. Try this function:
int sum_element(float ele[], unsigned int len){
int sum=24222.55455555; //mistake,should be : float sum = 0.0
char c = 0 ;
for(i=0;i<= len-1;i++){
printf("sum=%f, n= %d n2 = %d\n",sum,i,c);
}
return sum;
}
You should get a interesting value for n2.
I think the answer is that in the first case, the value being printed is not that of i at all. Two parameters are passed to printf which then reads two off. Those passed in are two ints, and then a double and and int are read off. Because the double is read off the stack first, when the int is read it is not from where the value of i was passed, hence the bogus value. Most likely the double covers enough of the stack to include both the passed ints.
Of course, results may vary, being undefined.

C language cygwin compiler, not sure why this is happening

My job is to prove fermats theory incorrect using c. so what i did was have nested loops, its pretty easy to read.
here is the code:
#include <stdio.h>
#include <math.h>
quadtest(unsigned long long int a, unsigned long long int b, unsigned long long int c, unsigned int n)
{
if ((pow(a,n)+pow(b,n))==pow(c,n))
return 1;
else
return 0;
}
main()
{
unsigned long long int a;
unsigned long long int b;
unsigned long long int c;
unsigned int n;
//a=1; b=1; c=1; n=1;
for(n=2; n<100; n++)
{
printf("\nn=%d",n);
for(c=1; c<500; c++)
{
printf("\ntrying now c=%d and n=%d",c,n);
for(b=1; b<500; b++)
{
if (quadtest(a,b,c,n)) break;
//printf("\nb=%d, n=%d",b,n);
}
for(a=1; a<500; a++)
{
if (quadtest(a,b,c,n)) break;
//printf("\na=%d, n=%d",a,n);
}
}
printf("\nthe right values to prove fermats theory wrong are n=%d,c=%d,b=%d,a=%d",n,c,b,a);
}
}
after being compiled, im getting "trying c=random number, n=0. n always equals 0 for some reason even though its never supposed to be 0.
im also getting something like "the right values to prove fermats theory wrong are n=99,c=500,b=0,a=500"
which once again, neither a, b, c, or n are supposed to be 0. not sure what the problem is
There are two clear problems with your code:
You define several variables, and each is initialised except for a. You call a function using a uninitialised. This is undefined behaviour and could explain your problem.
Secondly, you are using the incorrect specifier in printf. %d is used for int; %llu is for unsigned long long. Using the wrong specifier can lead to incorrect values being output.

Resources