Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Write a function unsigned int pose (unsigned int val, unsigned int base),
which returns a value val given in decimal notation for each given value val.
Value of val in the system can be construed with the base base. You can
assume that base is always between 2 and 9, and that val is sufficiently small to
on the target system to cause any number range violation.
Examples:
• pose (3,2) = 11 // 310 = 1 · 2 + 1 · 1 = 12
• pose (5,5) = 10 // 510 = 1 · 5 + 0 · 1 = 105
• pose (19,5) = 34 // 1910 = 3 · 5 + 4 · 1 = 345
• pose (5,6) = 5 // 510 = 5 · 1 = 56
• pose (7,7) = 10 // 710 = 1 · 7 + 0 · 1 = 107
• pose (543,9) = 663 // 54310 = 6 · 9
2 + 6 · 9 + 3 · 1 = 6639
Please note the following rules:
• Your output archive should contain exactly one file named "convert.c".
This file defines the function pose () and possibly other calls to be made by pose ()
Functions. Do not specify a main () function, do not include a makefile.
• You must not use loops (keywords for, while, goto).
• You must not use global variables.
• You may not use a library function.
Coderredoc's answer shows a nice solution using recursion. However, the only sensible interpretation of the question is to print val in base:
void pose (unsigned int val, unsigned int base){
if(val) {
pose(val/base,base);
printf("%c", (val%base)+'0');
}
}
int main(void)
{
pose (8,8); printf("\n");
pose (8,2); printf("\n");
pose (19,5); printf("\n");
return 0;
}
Output:
10
1000
34
First few hints or approach on how to solve it:-
Just solve the problem first.
Use loops and local variables and whatever is needed.
Once you solved it. Then look for applying the constraints.
The thing pretty easily indicates that you got to use recursion. Now rest is pretty easy - just decide what you will do in one loop. And transfer it to another recursive call with proper parameters.
unsigned int pose (unsigned int val, unsigned int base){
unsigned int ret = 0;
if(val)
ret=base*pose(val/base,base)+(val%base);
return ret;
}
Dissecting this code will reveal few things:-
I am just doing the necessary step in each step. In loop solution basically a digit is extracted. Here I do the same.And the reduced subproblem is then solved by another call to pose.
If you consider standard solution you will see the digits are extracted in reverse order. You don't want that. Instead of using another extra variable you should just use recursion to hold the result and do the necessary final operation with it. Reverse is done base*pose(val/base,base)+(val%base); using this specifically.
As discussed with Paul, the question is much more logical if we interpret it to simply "print the number in converted base b".
The solution will be similar like this:-The code next shown is of Paul's idea. Previous code is mine.
void pose (unsigned int val, unsigned int base){
if(val) {
pose(val/base,base);
printf("%c", (val%base)+'0');
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Good night, what's the best way in C to count the number of possibilities of UNIQUE anagrams in a string with the maximum length of 256 without allows repetitions caused by same letters? The input would be just in uppercase and only alphabet letters are allowed, A-Z. I got stuck in the worst case of the program that got 26! a very large number that overflow even my double. I think I'm very lost here, I'm not so good in C. The program just need to shows the number of possibilities, not the anagram. Like:
LOL = 3
HOUSE = 120
OLD = 6
ABCDEFGHIJKLMNOPQRSTUVWXYZ = 403291461126605635584000000
Thank you guys very much... I tried a lot and failed in every single tried, I'm in distress with it. The way I got more closer of do it was in Pascal, but it also failed in some tests, and I can't use Pascal anyway. I'm using CodeBlocks on Windows that compiles with GCC.
You should calculate factorial of the length of the given string divided by the factorial of the occurrence of every letter.
long double logFactorial (int i) {
return i < 2 ? 0.L : (logFactorial (i-1)+log(long double (i));
}
int countLetter(const char* str, char c) {
int res = 0;
while (str && *str) {
res += *str++ == c;
}
return res;
}
long double numPermutations(const char* str) {
auto res = logFactorial (strlen(str));
for (char c = 'A'; c<='Z'; c++) {
res -= logFactorial (countLetter (str,c));
}
return exp((long double)res);
}
Pay attention!
There are several people here who were correct by saying that factorial of 26 cannot be stored even in 64bit integer.
Therefore, I changed my calculation to the logarithmic of the factorial number and store it in long double which I hope is precise enough (I think that the exp() function is not precise enough)
Nevertheless you cannot use this result as an integer value, unless you find a way to store it in 128bit integer or bigger...
You should test it too if this fits your problem.
There is a faster way to calculate the factorial for this problem by storing the results of 0! up to 26! in an array of the size of [27].
I will leave it to you for asking another question.
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 7 years ago.
Improve this question
I just started doing codeforces problems, I started with problem 4-A (Watermelon), in which given an int x number of kilos the program will print "YES" if when you split the watermelon in two halves, each one has an even number of kilos, if not "NO".
My problem here is that I get "YES" when the input is 5, and it should be "NO"
Here is my code:
#include <stdio.h>
int main (int x) {
if((x/2) % 2 == 0) {
printf("YES");
}else {
printf("NO");
}
return 0;
}
The problem has nothing to do with mod, but with parameter passing.
The typical prototype for main is
int main(int argument_count, char *arg_list[], ...);
Calling my_exe 5 will set the first parameter x (argument_count) as 2, and the next unused parameter
arg_list[0] = "my_exe", // the first (0th) argument is the executable name
arg_list[1] = "5" // rest of parameters as arrays of chars
Calling my_exe without parameters sets x = 1 giving YES
Also if the argument x is a character '5' with the decimal value of 53 (0x35), the result is YES. This would be rather unconventional behavior, but definitely possible within some undisclosed IDE or coding framework.
Since the argument is an int then the division the remainder will be left. That is: 5 / 2 will result in a 2. Then that 2 mod 2 will give you a zero. What you should dp is to just put x % 2 inside the 'if' statement. So, with that 5 % 2 will give you a '1' which is thenn different to zero
if((x/2) % 2 == 0)
This condition is why you get yes for 5 as 5/2 is 2(as it is int) and 2%2 is 0.
just this will work -
if(x%2==0)
Since you are performing operation with integers, (5/2)=2, Hence you are getting "YES" as the output.Try this codeint main (int x) {
if(x % 4 == 0) {
printf("YES");
}else {
printf("NO");
}
return 0;
} If the condition is true, it will mean that the halves are even as well.
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 7 years ago.
Improve this question
sscanf() is great for the problem i'm facing, but it's doing something unexpected.
tmp is a line read in from a file, i need to parse out parts of the line into separate pieces of data. curritem is a struct with int dollar, int cent, cat[], int stock, and int history[].
The odd issue i'm having is that when %d picks up a double zero (00), it appropriately inserts integer zero into destination, but upon confronting a single zero (0), the integer is not added appropriately to the destination; for example, while collecting data pertaining to history[], all is well, adding 1, 4, 8, 2, 13, etc. to the array, but a single zero cuts everything off there, as if NULL terminated at that point, which i presume is related.
The code:
sscanf(tmp, "%d.%d%s %d %d %d", &curritem.dollar, &curritem.cent,
curritem.cat, &curritem.stock, &curritem.history[0],
&curritem.history[1]);
I have left out some indices of curritem.history[], as it clutters the necessary information.
Example of what i should get, if all integers were added correctly:
curritem.history[0...11] = 5 2 6 1 0 11 9 0 15 0 7 10
What actually results as of right now:
curritem.history[0...11] = 5 2 6 1
Something dies when sscanf() sees a single '0' via %d and adds that to &struct.intarray[n]
Any ideas?
Try not to recommend an entirely different solution to my general program function, sscanf() is working wonders in every other aspect.
Thank you for your time!
EDIT:
A snippet of exact input:
WL162343Fleece-Lined Double L Jeans 49.95PANTS 3 8 1 0 1 0 7 1 5 2 10 2 6
All information is acquired successfully until after the category- in this case, 'PANTS'.
With this example, my int array called history should hold the values
3 8 1 0 1 0 7 1 5 2 10 2 6
But upon printing every item in the array:
int n = 0;
for (n = 0; curritem.history[n]; n++) {
printf("%i ", curritem.history[n]);
}
The following output results:
3 8 1
EDIT:
The 'for' loop used for printing is incapable of distinguishing between an integer '0' and a null-termination of the array. Annoying.
What do you think that curritem.history[n] will return in the for's condition when it contains zero?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I can't find out the problem, it doesn't give me the right answer, for example: I put 1234567890, it gives me a series of strange number, I'm new so I cant post a picture:
#include <stdio.h>
int main()
{
int n,i;
int m[10];
while((n=getchar())!='\n') {
++m[n-'0'];
}
for(i=0;i<10;++i) {
printf("%d\n",m[i]);
}
return 0;
}
The basic problem is that you do not initialize the array
before counting digits.
int m[10] = {0};
Also you should handle non digit values so that the program
doesn't crash e.g.
while((n=getchar())!='\n')
{
if ( isdigit(n) )
{
++m[n-'0'];
}
}
( isdigit() is available if you include ctype.h )
Initialize your array contents to 0 instead of whatever randomly happens to be in memory, using:
int m[10]={0};
A few folks have already suggested including
int m[10] = {0};
This will work. Depending upon your compiler and optimization options it may not lead to the "best" code. An alternative, that I prefer is to invoke memset() to initialize the array to 0's before using it. Here is the modified program (also note that you do not need both n and i but an optimizing compiler would take care of that too):
#include <stdio.h> /* for getchar() and printf() */
#include <string.h> /* for memset() */
#include <ctype.h> /* for isdigit() */
int main(int argc, char* argv[])
{
int n, m[11];
memset(m, 0, sizeof(m)); /* initialize counters to zero's */
while ((n=getchar()) != '\n')
{
if (isdigit(n))
{
++(m[n-'0']);
}
else
{
++(m[10]);
}
}
for(n=0;n<10;n++)
printf("%c : %d\n",'0'+n, m[n]);
printf("Filtered characters: %d\n",m[10]);
return 0;
}
A sample run looks like this:
$ ./a.out
At 12:45 p.m. I ran to the 7-11 for a 48oz big gulp
0 : 0
1 : 3
2 : 1
3 : 0
4 : 2
5 : 1
6 : 0
7 : 1
8 : 1
9 : 0
Filtered characters: 42
$
As a final note, I looked at the generated assembly instructions output from gcc for different size m[]. Gcc generates inline code (sometimes looping and sometimes unrolled depending upon optimizations) for small sized arrays (say m[10] = {0};) and generates invocations of memset() as I have shown for larger sized arrays (say m[100] = {0};). A conclusion that can be drawn from this is that leaving the code as m[10] = {0}; allows the compiler to choose the best solution based upon what it knows about the target system which is almost certainly more than what you know.
Well since you didnt list what your problem is, I can only guess, but without trying to compile this, the most glaring issue is the buffer overflow on the "m" array. [Something which was wrong pointed out in the comments]
Edit
Also if you enter characters other than a number or newline, you'll overwrite memory outside the "m" array too.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to make a program that will divide a number by 2 only if that number is divisible by 2. I made it so that if the result of the number divided by 2 is a float, then divide it by two, like this:
int p;
printf("Percentage please: ");
scanf("%d", &p);
while (((p/2) != // a floating point value)
{
p = p/2;
}
But the problem is that I'm not sure if there is a function in the C standard libraries like isint() or iswholenumber(). Is there any function or any way I could implement something similar?
Any help would be appreciated.
You are looking for the modulo operation, that returns the rest of the division, so:
if( n % 2 == 1) // the number is not divisible by 2
if( n % 2 == 0) // divisible by 2
When you divide two ints the result is always an int (edit: truncated):
1/2 --> 0
2/2 --> 1
3/2 --> 1
So the logic p/2 is not a float does not make sense. Instead, as others have suggested, you want to use the modulo operator which returns the remainder of the division:
if( n % 2 ) // not divisible by 2
{
}
else // divisible by 2
{
}
Note: Since all integers that do not evaluate to 0 are equivalent to true you do not need to check n % 2 != 0.
you could ask the user for a string, then use int.TryParse
int x;
if (int.TryParse(inputString, out x))
{
// input is an integer.
}