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 2 years ago.
Improve this question
I am trying to solve the "3n+1" question and submit it on uva onlinejudge but every time it says that my code gives the wrong answer and unfortunately i can't find it's problem
here is the question: Problem 100
My Code:
#include <stdio.h>
int main()
{
unsigned long int n, m;
int max = 0;
scanf("%d %d", &n, &m);
int i;
for (i = n; i <m + 1; i++)
{
int ter = i;
int counter = 1;
while (ter != 1)
{
counter++;
if (ter % 2 == 1) { ter = 3 * ter + 1; }
else
ter = ter / 2;
if (ter == 1)
if (counter>max) { max = counter; }
}
}
printf("%d %d %d\n", n, m, max);
return 0;
}
The problem is clear. You are not following the instructions from the problem statement
For any two numbers i and j you are to determine the maximum cycle
length over all numbers between i and j.
The input will consist of a series of pairs of integers i and j, one
pair of integers per line. All integers will be less than 1,000,000
and greater than 0.
You only read one line of input and print that answer
You assume that i is less than j
Correct Solution:
#include <stdio.h>
int cycleSize(int x) {
int cycle = 1;
while (x != 1) {
if (x % 2 == 0) { //if even
x = x / 2;
} else { //if odd
x = x * 3 + 1;
}
++cycle;
}
return cycle;
}
int maxCycleSizeBetween(int a, int b) {
if (a > b) { //if b > a, swap them
int temp = a;
a = b;
b = temp;
}
int maxCycle = 0;
for (; a <= b; a++) {
int thisCycleSize = cycleSize(a);
if (thisCycleSize > maxCycle) {
maxCycle = thisCycleSize;
}
}
return maxCycle;
}
int main() {
int a, b; //input vars
while (scanf("%d %d", &a, &b) != EOF) {
printf("%d %d %d\n", a, b, maxCycleSizeBetween(a, b));
}
return 0;
}
The following function performs the requested calculation:
void n3plus1(int min, int max)
{
int i, n, len, lenmax=0;
for (i=min; i<=max; i++)
{
n= i; len= 1;
while (n!=1) {
if (n&1)
n= 3*n + 1;
else n= n/2;
len++;
}
if (len>lenmax) lenmax= len;
}
printf("Answer: %d %d %d\n", min,max,lenmax);
}
With the following tests:
void test(void)
{
n3plus1(22, 22);
n3plus1(1, 10);
n3plus1(100, 200);
n3plus1(201, 210);
n3plus1(900, 1000);
}
the output is:
Answer: 22 22 16
Answer: 1 10 20
Answer: 100 200 125
Answer: 201 210 89
Answer: 900 1000 174
Note: the "the maximum cycle length over all numbers between i and j" in the problem statement must be interpreted as including i and j.
The code assumes i<=j on input. The code excludes reading the input.
the following code implements the requirements
However, some online code contests expect a final blank line. You will need to determine those kinds of details.
#include <stdio.h>
int main( void )
{
size_t n1;
size_t m1;
char buffer[1024];
while( fgets( buffer, sizeof(buffer), stdin ) )
{
if( 2 != sscanf(buffer, "%lu %lu", &n1, &m1) )
{
break;
}
size_t n = n1;
size_t m = m1;
if( n1 > m1 )
{ // then first number greater than second so reverse for calculations
size_t temp = n;
n = m;
m = temp;
}
size_t maxCount = 0;
for (size_t i = n; i <= m; i++)
{
size_t ter = i;
size_t counter = 1;
while (ter != 1)
{
counter++;
if ( (ter & 0x01) == 1)
{ // then odd
ter = 3 * ter + 1;
}
else
{ // else even
ter = ter / 2;
}
// for testing only
// printf( "%lu: %lu, %lu\n", counter, i, ter );
}
if( maxCount < counter )
{
maxCount = counter;
}
}
printf("%lu %lu %lu\n", n1, m1, maxCount);
}
}
Note:
this code will exit if non numeric value entered
this code will exit if a EOF encountered -- this is expected
this code will fail if a negative number entered, however; the contest stipulation says that the numbers will be in the range 1...1000000 so no need to check for negative numbers
this code will exit if only one number on input line
this code will exit if only a <cr> is entered
Related
I am successful in identifying prime and composite from an array. But my qsort function seem to not have any effect when I print the output. I need the primes to be ascending and composite to be descending. When I run the code, it does not sort the output, though it identifies primes and composites.
#include <stdio.h>
#include <stdlib.h>
int compare_Asc(const void *a_void, const void *b_void) {
int a = *(int *)a_void;
int b = *(int *)b_void;
return a - b;
}
int compare_Desc(const void *a_void, const void *b_void) {
int a = *(int *)a_void;
int b = *(int *)b_void;
return b - a;
}
int main() {
int i = 0, n, x, p, c, z, w, j = 0, k = 0, cmpst, null;
int prm;
int prime[50], composite[50], input[50];
printf("How many inputs are you be working with?\nNote: 50 Maximum Inputs\n");
scanf("%d", &n);
printf("Enter the numbers.\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &input[i]);;
}
for (i = 0; i < n; i++) {
if (input[i] % 2 != 0) {
prime[p++] = input[i];
prm = p;
} else
if (input[i] >= 2 && input[i] % 2 == 0) {
composite[c++] = input[i];
cmpst = c;
}
}
printf("Prime Numbers:");
qsort(prime, prm, sizeof(int), compare_Asc);
for (i = 0; i < p; i++) {
printf("%d", prime[p]);
}
printf("Composite Numbers:");
qsort(composite, cmpst, sizeof(int), compare_Desc);
for (i = 0; i < c; i++) {
printf("%d", composite[c]);
}
return 0;
}
There are some major issues, in the posted code, worth mentioning.
Variables
Declaring all the variables at the beginning of the scope, instead of just before where they are used, can hide bugs.
Uninitialized variables, are an even worse source of errors, because their values are indeterminated.
int i=0, n, x, p, c, z, w, j=0, k=0, cmpst, null;
// ^ ^ ^^^^ ?
// ... Later, in the code:
prime[p++] = input[i];
// ^^^ What value is incremented?
// Where is [p++]? Is it inside the prime array?
A correct initialization would prevent undefined behavior.
int p = 0, c = 0;
int composite[50], input[50];
for(int i = 0; i < n ; ++i) {
if ( is_prime(input[i]) ) { // <-- More on this, later.
prime[p++] = input[i];
}
else {
composite[c++] = input[i];
}
}
Loops
This happens a couple of times, just because the code itself is duplicated (another code smell):
for(i=0;i<p;i++){
// ^^^^^^^^^^^ We want to iterate over [0, p).
printf("%d",prime[p]);
// ^ But this always prints the element one past the end
}
Even if it's just a simple loop, it could be a good idea to write a (testable and reusable) function
void print_arr(size_t n, int arr[n])
{
for (size_t i = 0; i < n; ++i) {
printf("%d ", arr[i]);
} // ^
putchar('\n');
}
// ... Later, in main:
print_arr(p, prime);
print_arr(c, composite);
Primes or composite
I am successful in identifying prime and composite from an array
Well, no. Not with this code, I'm sorry.
if (input[i]%2 != 0) { // Those are ALL the ODD numbers!
prime[p++]=input[i];
}
else if(input[i]>=2 && input[i]%2==0){ // Those are the EVEN numbers greater than 0
composite[c++]=input[i];
}
// What about 0 and the even numbers less than 0?
Not all the odd numbers are prime number (it's a little more complicated than that) and 2 itself is a prime, not a composite.
It's unclear to me if this is a terminology issue or if the snippet is only a placeholder for a proper algorithm. In any case, there are multiple examples of primality test functions in SE sites (I'm quite confident some are posted almost every day).
Overflow risk
See chux - Reinstate Monica's comment:
return a-b; risks overflow when a, b are large int values.
Consider return (a > b) - (a < b); for a full range solution.
Single letter variables names are to be avoided... except for i, j and k used in for() loops only.
You're not updating the index of the arrays c and p as the numbers are being printed out. The arrays are being sorted fine.
In the code below I also remove redundant variables, and rename n to input_count, c to compo_count and p to prime_count.
#include <stdio.h>
#include <stdlib.h>
int compare_Asc(const void *a_void, const void *b_void)
{
int a = *(int *) a_void;
int b = *(int *) b_void;
return a - b;
}
int compare_Desc(const void *a_void, const void *b_void)
{
int a = *(int *) a_void;
int b = *(int *) b_void;
return b - a;
}
int main ()
{
int i = 0;
int input_count = 0;
int prime_count = 0;
int compo_count = 0;
int prime[50];
int composite[50];
int input[50];
printf("How many inputs are you be working with?\nNote: 50 Maximum Inputs\n");
scanf("%d", &input_count);
printf("Enter the %d numbers.\n", input_count);
for (i = 0; i < input_count; i++)
{
scanf("%d", &input[i]);
}
for (i = 0; i < input_count; i++)
{
if (input[i] % 2 != 0)
{
prime[prime_count] = input[i];
prime_count += 1;
}
else if (input[i] >= 2 && input[i] % 2 == 0)
{
composite[compo_count] = input[i];
compo_count += 1;
}
}
printf("Prime Numbers:");
qsort(prime, prime_count, sizeof(int), compare_Asc);
for (i = 0; i < prime_count; i++)
{
printf("%d ", prime[i]); // <<-- HERE, not [p]
}
printf( "\n" );
printf ("Composite Numbers:");
qsort(composite, compo_count, sizeof(int), compare_Desc);
for (i = 0; i < compo_count; i++)
{
printf("%d", composite[i]); // <<-- HERE, not [c]
}
printf( "\n" );
return 0;
}
I am currently on my Uni homework and this is the last task. Its the 14th euler problem.
https://projecteuler.net/problem=14
So I am really new and i know that have a lot of crappy implementations. When executing this there is actually no output at all. I've been running this for 3 Minutes because i thought it needed to "load"..
My Task is to have a working function that calculates the Length and then take this length and compare it to have the longest chain as the "Final" output.
I tried to have a Loop that calculates the length for every i in 1000000 and then save this number into an array with the same size.
At the end of the Loop I want to compare the last length with the current and save the longer into the var if its longer.
I am stuck for like the past 2 hours
Here is my current Code:
#include <stdio.h>
#include <math.h>
int number = 1000000;
long sequence = 0;
int seqLen = 0;
int startingNum = 0;
int currLen = 0;
unsigned calculateCollatzLength(unsigned n){
int ans = 1;
while (n != 1) {
if (n & 1) {
n = 3 * n + 1;
} else {
n >>= 1;
}
ans ++;
}
currLen = ans;
return currLen;
}
int main() {
int cache[number];
for(int i = 0; i <= number; i++){
calculateCollatzLength(i);
cache[i] = currLen;
if (cache[i] > seqLen) {
seqLen = cache[i];
startingNum = i;
}
}
printf("The Longest Collatz Chain from 1 to 1000000 is %d long and has the starting number %d \n", seqLen, startingNum);
}
Hope that this is kind of understandable to ask in on this since this is my 3rd Question and it kind of feels like cheating asking but i dont know who to ask or cant find any answers :(
Here's a cleaned-up working version of your code. There's no need for a cache, and int64_t is a safer bet than unsigned (which is likely to be 32 bits) to avoid overflows. Your use of global variables was confusing and unnecessary – you can simply return the length of the sequence and find the maximum in main.
#include <stdio.h>
#include <stdint.h>
int collatz(int64_t n){
int len = 1;
while (n != 1) {
if (n & 1) {
n = 3 * n + 1;
} else {
n >>= 1;
}
len++;
}
return len;
}
#define N 1000000
int main(void) {
int longest_i = 0;
int longest = 0;
for(int i = 1; i <= N; i++){
int len = collatz(i);
if (len > longest) {
longest_i = i;
longest = len;
}
}
printf("**collatz(%d) = %d\n", longest_i, longest);
}
The problem is to find the number i<=n, n<=500000 for which the longest collatz series exists.
Collatz series for a number n terminates at 1, and the conditions are
if n is even, next term = n/2
if n is odd, next term = 3*n + 1
Well as a matter of fact, the collatz series always terminates at 1 for all numbers.
Hence any number won't repeat in its collatz series. Using this fact, I have written the following code
LOGIC:
I start a while loop, that goes till n and for each iteration, I store the length of the series for that i.
If i occurs in the series of some n >= r > i, then i terminate the loop and add the length of i to r.
For example, say series of 3 is 3, 10, 5, 16, 8, 4, 2, 1. Now the length corresponding to 2 will already be stored in the series_length array, so I use that value.
Then the for loop next to that, finds the longest series and displays the answer.
The code works fine for n <= 1818 to be precise, but shows segmentation fault onwards (dunno why :(). Please help
CODE :
#include <stdio.h>
int length = 0, series_length[500000], maxlength = 0;
void store_length(int n) {
while(n > 1 && series_length[n] == 0) {
length++;
if(n%2 == 0) {
n = n/2;
}
else {
n = 3*n + 1;
}
}
length += series_length[n];
}
int main() {
int n, i = 1, result;
scanf("%d", &n);
series_length[1] = 1;//redundant statement
while(i <= n) {
store_length(i);
series_length[i] = length;
length = 0;
i++;
}
for(int i = 1;i <= n; i++) {
if(maxlength <= series_length[i]) {
maxlength = series_length[i];
result = i;
}
}
printf("%d %d\n", result, maxlength);
return 0;
}
INPUT-
10
OUTPUT-
9 20 (AS Expected)
INPUT-
100000
OUTPUT-
Segmentation Fault
Expected-
77031 351
Your value for n goes outside the range.
You have a line n = 3*n + 1; in the function store_length
Running this with the gdb with input as 100000 gives
Thread 1 received signal SIGSEGV, Segmentation fault.
0x0000000000401545 in store_length (n=532060) at 29_01.c:6
6 while(n > 1 && series_length[n] == 0) {
(gdb) p n
$1 = 532060
only store it if it fits
... and use it if it already has been computed
avoid global variables
prefer unsigned values
[use descriptive variable names]
#include <stdio.h>
#define THE_SIZE 500000
unsigned series_length[THE_SIZE]= {0,};
unsigned get_length(unsigned val) {
unsigned steps;
for (steps=0; val > 1 ; steps++) {
if (val < THE_SIZE && series_length[val]) { steps += series_length[val]; break; }
if(val %2 ) val = 3*val + 1;
else val /= 2;
}
return steps;
}
int main( int argc, char **argv) {
unsigned top, val , result;
unsigned best,maxlength ;
sscanf(argv[1], "%u", &top);
series_length[1] = 1;//redundant statement
best = maxlength = 0;
for(val=1;val <= top; val++) {
result = get_length(val);
// store it if it fits;
if(val<THE_SIZE) series_length[val] = result;
if (result < maxlength) continue;
best = val; maxlength = result;
}
printf("%u %u\n", best, maxlength);
return 0;
}
Finally, just for fun, make the array smaller
#define THE_SIZE 500
, and the program should give the same result for a given value. (it does)
You get the maximum value 24,648,077,896 with n = 487039.
You must thus use the type long long int for n and you should use an array of 24,648,077,896 integers to avoid a segmentation fault. Unfortunately I never succeeded in allocating a block of 100GB. Your optimization is thus not viable.
Without the array optimization I can scan all 500000 n values in 265ms.
Here is my code:
#include <stdio.h>
int collatz_length(int n) {
int length = 0;
long long int v = (long long int)n;
while (v > 1) {
if ((v&1) == 0)
v = v / 2;
else
v = v*3 + 1;
length++;
}
return length;
}
int main() {
int max_i, max_l = 0;
for (int i = 500000; i > 0; i--) {
int l = collatz_length(i);
if (l > max_l){
max_l = l;
max_i = i;
}
}
printf("i: %d l: %d\n", max_i, max_l);
return 0;
}
This is my first time learning C. So I have to write a code that can find the second largest number from any inputted numbers.
The code is:
#include <stdio.h>
int main() {
int x, max, max2;
max = max2 = -1;
while (scanf("%d", &x) != EOF) {
if (x > max) {
max2 = max;
max = x;
} else if (x > max2) {
max2 = x;
}
}
printf("%d\n", max2);
return 0;
}
The problem is, if I enter 1 2 3 4 5 here, the answer should be 4, as 4 is the second max number. But the code should work on any inputted number. I just couldn't figure it out.
I have to use Linux terminal and vim to solve it. I made a input file in terminal using vim input and made a file and input 1 2 3 4 5 there. But when I run the code using ./a.out <input, it still shows 5. How do I solve this?
What do you mean by "any inputted number" ? Non sorted input ? Negative as well ?
Here is a function which takes a list of positive integers and return the second maximum, or -1 if an error is encountered (not enough arguments). To adapt to your needs.
int snd_max(int length, int* args) {
int max, max2;
max = -1;
max2 = -1;
for (int i = 0; i< length; i++) {
if (args[i] > max) {
max2 = max;
max = args[i];
} else if (args[i] > max2 {
max2 = args[i]
}
}
return max2;
I made it easy for myself and replaced your input with an array.
int main (void)
{
char lst [] = { 10, 11, 2, 33 }; // my input (must be char because
// I use sizeof to determine the number of inputs)
int max = -1; // biggest
int submax = -1; // 2nd biggest
if (sizeof (lst) < 2) // must be > 1 to find 2 biggest numbers
{
printf ("bad");
return 0;
}
for (int i = 0; i < sizeof (lst); i ++)
{
int x = lst [i];
if (x > max)
{
submax = max;
max = x; // new biggest makes the old biggest to 2nd biggest
}
else // its not biggest but maybe 2nd biggest
{
if (x > submax)
{
submax = x;
}
}
printf ("\n%d: check %d - max=%d, submax=%d\n", i, x, max, submax);
}
return 0;
}
I am trying to solve 12503 problem on UVA online judge. I think I have figured out the solution, but it gives me TLE. Here is the problem :
You have a robot standing on the origin of x axis. The robot will be given some instructions.
Your task is to predict its position after executing all the instructions.
• LEFT: move one unit left (decrease p by 1, where p is the position of the robot before moving)
• RIGHT: move one unit right (increase p by 1)
• SAME AS i: perform the same action as in the i-th instruction. It is guaranteed that i is a positive
Input
integer not greater than the number of instructions before this.
The first line contains the number of test cases T (T <= 100). Each test case begins with an integer n (1 <= n <= 100), the number of instructions. Each of the following n lines contains an instruction.
Output
For each test case, print the final position of the robot. Note that after processing each test case, the
robot should be reset to the origin.
Sample Input
2
3
LEFT
RIGHT
SAME AS 2
5
LEFT
SAME AS 1
SAME AS 2
SAME AS 1
SAME AS 4
Sample Output
1
-5
Here is my code in C:
#include <stdio.h>
char com[102][20];
int command(char comd[], int pos);
int main() {
int t;
int pos;
int i, n;
char tmp[20];
scanf("%d", &t);
for(i = 0; i < t; i++) {
scanf("%d", &n);
int j;
pos = 0;
for (j = 0; j < n; j++) {
gets(com[j]);
if (strcmp(com[j], "LEFT") == 0)
pos--;
else if(strcmp(com[j], "RIGHT") == 0)
pos++;
else {
pos = command(com[j], pos);
}
}
printf("%d\n", pos);
}
return 0;
}
int command(char comd[], int pos) {
if (strcmp(comd, "LEFT") == 0) {
pos--;
return pos;
}
else if (strcmp(comd, "RIGHT") == 0) {
pos++;
return pos;
}
else{
int a = atoi(&comd[8]);
return command(com[a-1], pos);
}
}
Is there any suggestion why this code gives TLE ?
In the int command(char comd[], int pos) function, you are using recursive call at the last line. This may lead to TLE.
To solve this problem you can use another array to store the number of steps taken by the robot at a command. You just have to access the index of the array later to get step at a previous command.
Here is how I would do it-
#include <stdio.h>
#include <string.h>
int move[110];
int getMove(char inp[], int);
int main()
{
int t, n;
char inp[50];
scanf(" %d ",&t);
while(t--)
{
scanf(" %d ",&n);
int i, pos = 0;
for(i = 0; i < n; i++)
{
gets(inp);
pos += getMove(inp, i);
}
printf("%d\n",pos);
}
return 0;
}
int getMove(char inp[], int i)
{
if(inp[0]=='S')
{
int j;
sscanf(strrchr(inp,' ')," %d",&j);
move[i] = move[j - 1];
}
else
{
move[i] = (inp[0] == 'L') ? -1 : 1;
}
return move[i];
}