Here is the code for "The Next Palindrome" which I wrote in C:
#include<stdio.h>
int main(void)
{
int check(int); //function declaration
int t,i,k[1000],flag,n;
scanf("%d",&t); //test cases
for(i=0; i<t; i++)
scanf("%d",&k[i]); //numbers
for(i=0; i<t; i++)
{
if(k[i]<=9999999) //Number should be of 1000000 digits
{
k[i]++;
while(1)
{
flag=check(k[i]); //palindrome check
if(flag==1)
{
printf("%d\n",k[i]); //prints if it is palindrome and breaks
break;
}
else
k[i]++; //go to the next number
}
}
}
return 0;
}
int check(int n)
{
int rn=0;
int temp=n;
while(n!=0)
{
rn=rn*10+n%10; //reversing
n=n/10;
}
if(rn==temp) //number is palindrome
return 1;
else //number is not a palindrome
return 0;
}
It is a beginner level problem from SPOJ.
I tried to run this code on Codeblocks and it ran fluently.
In SPOJ, why is it showing wrong output?
In SPOJ, why is it showing wrong output?
This is nice solution and it works for small inputs, however it will not pass SPOJ for several reasons.
The requirement is:
A positive integer is called a palindrome if its representation in the
decimal system is the same when read from left to right and from right
to left. For a given positive integer K of not more than 1000000
digits, write the value of the smallest palindrome larger than K to
output. Numbers are always displayed without leading zeros.
Input:
The first line contains integer t, the number of test cases.
Integers K are given in the next t lines.
So which requirements are broken in your program?
1) Your assumption is that only 1000 numbers will be given for processing since
you declared
k[1000]
wrong, the number of lines is given in first line. It could be much more than 1000. You have to dynamically assign the storage for the numbers.
2)
The line
if(k[i]<=9999999)
assumes that input is less than 9999999
- wrong, the requirement says positive integer K of not more than 1000000 digits which imply that much larger numbers e.g. 199999991 also have to be accepted.
3) The statement
For a given positive integer K of not more than 1000000 digits
as well as warning
Warning: large Input/Output data, be careful with certain languages
leads us to conclusion that really big numbers should be expected!
The int type is not a proper vehicle for storing such big numbers. The int will fail to hold the value if the number is bigger than INT_MAX +2147483647. (Check C Library <limits.h>)
So, how to pass SPOJ challange?
Hint:
One of the possible solutions - operate on strings.
Related
Problem:
You are provided an array A of size N that contains non-negative integers. Your task is to determine whether the number that is formed by selecting the last digit of all the N numbers is divisible by 10.
Note: View the sample explanation section for more clarification.
Input format
First line: A single integer N denoting the size of array Ai.
Second line: N space-separated integers.
Output format:
If the number is divisible by 10 , then print Yes . Otherwise, print No.
Constraints:
1<=N<=100000
0<=A[i]<=100000
i have used int, long int ,long long int as well for declaring N and 'm'.But the answer was again partially accepted.
#include <stdio.h>
int main() {
long long int N,m,i;
scanf("%ld", &N);
long data[N];
for(auto i=0; i<N; i++) {
scanf("%ld", &data[i]);
}
// write your code here
// ans =
m=(data[0]%10);
for(i=1; i<N; i++) {
m=m*10;
m=(data[i]%10)+m;
}
if(m%10!=0 && m==0) {
printf("Yes");}
else{
printf("No");
}
return 0;
}
Try making a test suite, that is, several tests for which you know the answer. Run your program on each of the tests; compare the result with the correct answer.
When making your tests, try to hit also corner cases. What do I mean by corner cases? You have them in your problem statement:
1<=N<=100000
0<=A[i]<=100000
You should have at least one test with minimal and maximal N - you should test whether your program works for these extremes.
You should also have at least one test with minimal and maximal A[i].
Since each of them can be different, try varying them - make sure your program works on the case where some of the A[i] are large and some are small.
For each category, include tests for which the answer is Yes and No - to exclude the case where your algorithm always outputs e.g. Yes by mistake.
In general, you should try to make tests which challenge your program - try to prove that it has a bug, even if you believe it's correct.
This code overflows:
m=(data[0]%10);
for(i=1; i<N; i++) {
m=m*10;
m=(data[i]%10)+m;
}
For example, when N is 1000, and each of the input items A[i] (scanned into data[i]) ends in 9, this attempts to compute m = 99999…99999, which grossly overflows the capability of the long long m.
To determine whether the numeral formed by concatenating a sequence of digits is divisible by ten, you merely need to know whether the last digit is zero. The number is divisible by ten iff data[N-1] % 10 == 0. You do not even need to store these numbers in an array; simply use scanf to read but ignore N−1 numerals (e.g., scanf("%*d")), then read the last one and examine its last digit.
Also scanf("%ld", &N); wrongly uses %ld for the long long int N. It should be %lld, or N should be long int.
An integer number given in decimal is divisible by ten if, and only if, its least significant digit is zero.
If this expression from your problem:
the number that is formed by selecting the last digit of all the N numbers
means:
a number, whose decimal representation comes from concatenating the least significant digits of all input numbers
then the last (the least significant) digit of your number is the last digit of the last input number. And that digit being zero is equivalent to that last number being divisible by 10.
So all you need to do is read and ignore all input data except the last number, then test the last number for divisibility by 10:
#include <stdio.h>
int main() {
long N, i, data;
scanf("%ld", &N);
for(i=0; i<N; i++)
scanf("%ld", &data); // scan all input data
// the last input number remains in data
if(data % 10 == 0) // test the last number
printf("Yes");
else
printf("No");
return 0;
}
I have an assignment to make a program that calculates the iterative digital sum of an integer, eg. doing the digital sum until the result is a single digit. The catch is that the number they test for are much greater that can be stored in any int type (around 10^40000) so my idea was to do the first sum using getchar(), adding up the number digit by digit.
My code
#include <stdio.h>
int main(){
long int n=0;
int c;
//first sum
while((c=getchar())!=EOF && c!='\n'){
n+=(c-'0');
}
//iterative summing
long int s;
do{
s=0;
while(n>0){
s+=n%10;
n/=10;
}
n=s;
}while (n>=10);
printf("%ld\n",s);
return 0;
}
It worked for relatively short numbers, however after some point, the sum would come out wrong. So I tried setting up a variable that'd get incremented with each character summed, and it would always show the number of 4095.
So my question is, is there an 11-bit limit to how many characters you can get from stdin using getchar()? If so, is there a way to get more?
I have just started competitive programming in SPOJ.I'm confused from sometime why i'm getting runtime error in ideone.The question is:
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output
For each K, output the smallest palindrome larger than K.
Example
Input:
2
808
2133
Output:
818
2222
My program:
#include <stdio.h>
int main(void)
{
int t,i,reverse,same;
scanf("%d",&t); //t is no. of test cases
int num[t]; //num[t] is array of t elements
for(i=0;i<t;i++)
scanf("%d",&num[i]);
i=0; //since i will be equal to t therefore i is assigned to 0.
while(t--)
{
if(num[i]<=1000000)
{
while(num[i]++)
{
reverse=0;
same=num[i];
while(same>0)
{
reverse=reverse*10;
reverse=reverse+same%10;
same=same/10;
}
if(reverse==num[i])
printf("%d",reverse);
printf("\n");
if(reverse==num[i])
break;
}
}
i++;
}
return 0;
}
I don't know where i'm wrong.I'm sorry i'm asking this question may this question is asked by someone before.I tried to find the result but could not get the answer.Thankyou in advance and sorry for my bad english.
The question doesn't say that the number will be less than 1000000. It says that the number has less than 1 million digits. A number with a million digits looks like this
591875018734106743196734198673419067843196874398674319687431986743918674319867431986743198674319876341987643198764319876341987643198764319876431987643198763419876431987643198764319876139876...
You can't use scanf to read a number that has a million digits, and you can't store that number in an int.
The most likely reason for your error to occur is some memory fault. Keep in mind that online judges/compilers limit your available memory and if you try to allocate/use more memory than available, you get a runtime error. This also happens on your machine, but usually you have a lot more memory available for your program than in the case of online judges.
In your case, you could reduce the memory usage of your program by changing the data type of the num array from int to something like short or even char.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm new to C. I have a class assignment to display a number in a vertical format. If the user enters 5678, the instructor want it to display vertically to the screen in a single column as:
8
7
6
5
Second part of assignment is to find the largest divisor of the same number.
I'm totally lost. I'm getting the NUM value from another function. formula seems to work on even numbers, but on odd.
int divisor (int NUM)
{
int index, count=0;
for(index=2;index<=(NUM/2);index=index+1)
{
if(NUM%index==0)
count++;
}
printf("\n\nThe largest divisor of %d is %d\n",NUM, index-1);
return(index);
}
To display the number vertically:
1. get least significant digit,
2. print it and print new line,
3. shift number to the right by one digit
4. goto 1
Algorithm terminates when the number is zero. Call the input number n; getting the least significant (rightmost) digit can be done with n % 10. Right shift can be done with n = n / 10.
For the second part, observe that the largest divisor cannot be more than n/2 (because n = 2 * n/2). So try all number from n/2 down to 1 and break once you find a divisor. You will find the largest divisor because you are considering numbers in decreasing order. To check that x divides y use y % x == 0.
A second way it to check numbers from sqrt(n) down to 1. If m divides n, we can write n = m * k for some k. Now you take max(m, n/m) and continue.
Hope this helps :)
For the first part, there are many ways to approach this. But, without using too many of the standard library functions which seems to be a level appropriate for the question, I think the easiest way would be to take the numbers as a character array. Then access each value through it's index in the character array. This requires only the stdio.h header file. Some quick notes: simply use printf to print the value contained at each index, and throw the newline \n character at the end. If you wanted convert the string to an integer, you can do that very easily using the function atoi() which can be found in stdlib.h. If you want to print out backward, you can simply traverse the array backward.
void displayvert(char str[])
{
int i;
for (i = 0; str[i] != '\0'; ++i) {
printf("%c\n", str[i]);
}
}
Also many ways to approach the second, but in this case for the second question I think I'd use the modulus operator and track the highest value where the result is zero. In order for this to work with the single user provided input, I actually needed atoi() which is in the stdlib.h header. Basically, starting from the value one you'll increase the value up the integer just below the value of 'num' itself. And, if the remainder is zero when you when you divide by it (the purpose of using the modulus operator) then you know it's divisible. Because we're ascending from 1 to the number itself, the last value to return a remainder of zero is the greatest common divisor.
void getgcd(int num)
{
int i, gcd;
// remember, you can't do x % 0!
for (i = 1; i < num; i++) {
if ((num % i) == 0 ) {
gcd = i;
}
}
printf("The greatest common divisor is: %d\n", gcd);
}
Main function and prototypes here so you can see how it all tied together. A couple of quick notes (1) 11 digits was arbitrary; but it's important to note that we used 10 digits for the total input value (you can add checks to this to enforce) and reserved the 11th (at index 10) to allow space for the null terminating character \0. (2) Use scanf to grab input; note that because character arrays do not require the address operator & because it defaults to that.
#include <stdio.h>
#include <stdlib.h>
void displayvert(char str[]);
void getgcd(int num);
int main()
{
char input[11]; // additional character added for \0
printf("Please enter a value up to 10 digits: ");
scanf("%s", input);
displayvert(input);
getgcd(atoi(input));
return 0;
}
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 :)