I am converting decimal to binary and I need my output to be 32 (bits?) long. This works as I intend, but I am not getting the leading zeros, for instance, the input "3" gives me "11", instead of "00000000000000000000000000000011"
int i = 0;
int bi[31];
while(num > 0){
if(num % 2 == 0)
bi[i] = 0;
else
bi[i] = 1;
i++;
num = num / 2;
}
for(int j = i - 1; j >= 0; j--){
printf("%d", bi[j]);
}
I originally thought this would be as simple as changing my printout to just loop down from 31 to 0 and print out all the contents of the array, assuming zeros would be in everything not in my bi[] array. But that does not work :)
Thanks
for(int j = 0; j < 32; j++) // this for loop is initializing all the places with zeroes
{
b[j] = 0;
}
i = 31 // starting from the leftmost place of the array
while(num > 0) //as the values in the array gets updated the remaining place is left with trailing
{
if(num % 2 == 0)
bi[i] = 0;
else
bi[i] = 1;
i--;
num = num / 2;
} zeroes
for(int j = 0; j < 32; j++){
printf("%d", bi[j]);
}
Due to the LIFO nature of this problem, consider a recursive (stack-based) solution:
#include <stdio.h>
#include <limits.h>
void recFoo(int num,int index)
{
if (index > 0)
recFoo(num/2, index-1);
printf("%d", num%2);
}
void foo(int num)
{
recFoo(num, sizeof(num)*CHAR_BIT);
}
The reson is because the first loop only loops twice, which is the highest set bit in the input. The first loop needs to loop unconditionally the number of bits you want, and so should the printing loop.
First of all you need a 32 long array. Try this one..... Initializing your array
void foo (int num) {
int i = 31;
int bi[32] = {0};
while(num > 0){
if(num % 2 == 0)
bi[i] = 0;
else
bi[i] = 1;
i--;
num = num / 2;
}
for(int j = i - 1; j >= 0; j--){
printf("%d", bi[j]);
}
Related
So I have to write a code for school. I did, but my outputs are not the way they asked for. This code gives me prime number between 2 different numbers. So i have to print those numbers in rows. But yeah there are getting zeros between the answers below you can see what I mean. How can I fix this?
#include <stdio.h>
int is_prime (int number)
{
int is_prime= 1, i;
if (number < 2)
{
is_prime = 0;
}
else
{
for(i = 2; (i * i) <= number; i++)
{
if ((number % i) == 0)
{
is_prime = 0;
break;
}
else
{
is_prime = 1;
}
}
}
return is_prime;
}
int main (void)
{
int lower_limit, upper_limit, i;
scanf("%d\n%d", &lower_limit, &upper_limit);
for(i = lower_limit; i <= upper_limit; i++)
{
if (is_prime (i))
{
printf("\n%d", i);
}
else
{
printf("\n%d", is_prime(i));
}
}
return 0;
}
Output
0
11
0
13
0
0
0
17
0
19
0
Reference
11
13
17
19
It's in this if block:
if (is_prime (i))
{
printf("\n%d", i);
}
else
{
printf("\n%d", is_prime(i));
}
What this says is "if the number is prime print it, otherwise print whether it is prime (which at this point you've established it's not)".
Just get rid of the else block.
If the number is prime number just print it. No else needed - even worse it is incorrect.
You can simplyfy the the is_prime function
int is_prime (int number)
{
int is_prime = number > 1, i;
for(i = 2; (i * i) <= number; i++)
{
if ((number % i) == 0)
{
is_prime = 0;
break;
}
}
return is_prime;
}
int main (void)
{
int lower_limit, upper_limit, i;
scanf("%d\n%d", &lower_limit, &upper_limit);
for(i = lower_limit; i <= upper_limit; i++)
{
if (is_prime (i))
{
printf("\n%d", i);
}
}
return 0;
}
https://godbolt.org/z/4d8qhx
Another problem: overflow.
Avoid int overflow in i*i, which is undeifned behavior (UB).
This can happen when number is a prime near INT_MAX.
// for(i = 2; (i * i) <= number; i++)
for(i = 2; i <= number/i; i++)
A good compiler will see the nearby number%i and number/i and emit efficient code for the two of them, thus not incurring an expensive 2nd operation.
The below also overflows when upper_limit == INT_MAX
for(i = lower_limit; i <= upper_limit; i++)
Perhaps
for(i = lower_limit; i - 1 < upper_limit; i++)
OK as long as lower_limit > INT_MIN.
I'm trying to create a function that compares two four digit numbers and
returns the number of similar digits between the two. For example, with a generated number of 4311 and the user entered 1488,
the score should return 2 (4 and 1).
If it was 4311 and the other is 1147,
the score should return three (1, 1 and 4). I don't know why it isn't giving me the right outputs, hope you can help.
int getSameDigitScore(int playerGuess, int generatedNum) {
int score = 0;
int i;
int j;
int k;
int generatedNumArray[4];
int playerGuessArray[4];
// turns playerGuess into an array
while (playerGuess > 0 ) {
i = 0;
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
// turns generatedNum into an array
while (generatedNum > 0) {
i = 0;
generatedNumArray[i] = generatedNum % 10;
i++;
generatedNum /= 10;
}
// compares the two arrays
for (k = 3; k >= 0; k--) {
for (j = 3; j >= 0; j--) {
if (generatedNumArray[k] == playerGuessArray[j]) {
score++;
playerGuessArray[j] = 0;
j = -5;
}
}
}
return score;
}
You are assigning i = 0 inside the while loop while generating the playerGuessArray and generatedNumArray. Due to which the playerGuess and generatedNumArray array will have elements as first digit of your number 0 0 0 .
Move the initialization out of the loop.
int getSameDigitScore(int playerGuess, int generatedNum) {
int score = 0;
int i, j, k, n;
int generatedNumArray[4];
int playerGuessArray[4];
// turns playerGuess into an array
i = 0; // This has been out of while loop
while (playerGuess > 0 ) {
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
// turns generatedNum into an array
int n = 0; // This has been out of the while loop
while (generatedNum > 0) {
generatedNumArray[n] = generatedNum % 10;
n++;
generatedNum /= 10;
}
// compares the two arrays
for (k = 3; k >= 0; k--) {
for (j = 3; j >= 0; j--) {
if (generatedNumArray[k] == playerGuessArray[j]) {
score++;
playerGuessArray[j] = 0;
j = -5;
}
}
}
return score;
}
int main() {
int m;
n = getSameDigitScore(1231, 2342);
printf("Score is: %d\n", m);
}
You're re-initializing increment variable i on every iteration which should be moved out of the while loop. With that moved out the above code works fine.
There are the following issues with the code.
You are initializing the integer i inside the while loop. This needs to be done before the loop for each loop.
You need a separate array to get the output of equal digits. See AnswerArray in code below. Also it is a good design practice to pass this array to the function and clear this array inside the function.
In the last for loop, you should break from the inner loop after getting a match. This is to take care of cases where playerGuess == 1222 and generatedNum = 1111 In the code shown this will result in a score of 1.
See the final code below with some test cases.
int getSameDigitScore(int playerGuess, int generatedNum, int *AnswerArray) {
int score = 0;
int i;
int j;
int k;
int generatedNumArray[4] = {0};
int playerGuessArray[4] = {0};
memset(AnswerArray,0,4*sizeof(int));
// turns playerGuess into an array
i = 0;
while (playerGuess > 0 ) {
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
// turns generatedNum into an array
i = 0;
while (generatedNum > 0) {
generatedNumArray[i] = generatedNum % 10;
i++;
generatedNum /= 10;
}
// compares the two arrays
score=0;
for (k = 3; k >= 0; k--) {
for (j = 3; j >= 0; j--) {
if (generatedNumArray[k] == playerGuessArray[j]) {
AnswerArray[score++] = generatedNumArray[k];
playerGuessArray[j] = -1;
break;
}
}
}
return score;
}
int main(void)
{
int AnswerArray[4],score;
score = getSameDigitScore(4311,1488,AnswerArray);
printf ("\nScore = %d \n Answer Array = ",score);
for (int i=0; i<score; i++)
{
printf ("%d ",AnswerArray[i]);
}
score = getSameDigitScore(4311,1147,AnswerArray);
printf ("\nScore = %d \n Answer Array = ",score);
for (int i=0; i<score; i++)
{
printf ("%d ",AnswerArray[i]);
}
score = getSameDigitScore(1222,1111,AnswerArray);
printf ("\nScore = %d \n Answer Array = ",score);
for (int i=0; i<score; i++)
{
printf ("%d ",AnswerArray[i]);
}
score = getSameDigitScore(1111,1222,AnswerArray);
printf ("\nScore = %d \n Answer Array = ",score);
for (int i=0; i<score; i++)
{
printf ("%d ",AnswerArray[i]);
}
}
The initializing i=0 which you made inside the loop should be outside the loop.
while (playerGuess > 0 ) {
i = 0;
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
If the initialization is inside the looop then,
Everytime playerGuessArray[0] value will be updated.
FYI:
If playerGuess can contain 0 aat the begin of four digit like 0123
For example, playerGuessValue is 0123, Then by using
while (playerGuess > 0 ) {
i = 0;
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
playerGuessArray will contain only [1,2,3] instead of [0,1,2,3].
So, the better solution would be taking two temporary variables and checking last digit one by one.
Like this:
int temp1=playerGuess, temp2=GeneratedNum;
int i=0;
bool flag = true;
while(flag && i < 4){
if(temp1%10 != temp2%10){
flag = false;
}
temp1 /= 10;
temp2 /= 10;
i++;
}
if(flag){
score++;
}
FYI:
Debugging will help you in finding out these little mistakes.So, try to debug your code with multiple inputs and verify your answer.
Here are few reference on how to debug:
https://blog.hartleybrody.com/debugging-code-beginner/
https://www.codementor.io/mattgoldspink/how-to-debug-code-efficiently-and-effectively-du107u9jh%60
Thanks.
I have implemented a basic program which generates 10 random and unique numbers from 1 to 10 as shown below. I have added an extra part in which I want the binary representation for each unique and random number. My program looks like this.
int value=1, loop, loop1, get=0, x, arr[10], array[20], count, i =0, y;
srand(time(NULL));
for (x = 0; x < 10; x++)
{
for (count = 0; count < 10; count++) {
array[count] = rand() % 10 + 1; //generate random number between 1 to 10 and put in array
}
while (i < 10) {
int r = rand() % 10 + 1; // declaring int r
for (x = 0; x < i; x++)
{
if (array[x] == r) { //if integer in array x is equal to the random number generated
break; //break
}
}
if (x == i) { //if x is equal to i then
array[i++] = r; //random number is placed in array[10]
}
}
for (y = 0; y < 10; y++) {
printf("unique random number is %d\n", array[y]);
array[y] = value;
for (loop = 0; loop < 1000; loop++)
{
if (value <= 1) { arr[loop] = 1; break; } //if value is 1 after dividing put 1 in array
if (value % 2 == 0) arr[loop] = 0;
else arr[loop] = 1;
value = value / 2;
}
for (loop1 = loop; loop1 > -1; loop1--)
printf("%d", arr[loop1]);
printf("\n");
}
}
My problem is that The binary value for each random unique number is being given as 1. In this program it is seen that I initialised value=1 and this can be the source for my error, however when I remove this I get an error stating that the local variable is uninitialised.
The first part of my program which generates the unique numbers is working fine, however the second part where I am converting to binary is not.
EDIT: I tested The second part of my program and it works well on it's own. The problem must be the way I am combining the two programs together.
Statement array[y] = value overrides the previously generated random values with constant 1.write
value = array[y];
Here is the commented code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//function to check unique random number
int check(int array[],int count,int val)
{
int i=0;
for( ;i<count ;++i )
{
if (array[i]==val)
return 1;
}
return 0;
}
int main(void)
{
int value,loop, loop1, get, x, arr[10];
int oldRandoms[10]; // array to preserve old random values
srand(time(NULL));
for (x = 0; x < 10; x++)
{
do // do while to get only unique random number
{
get = rand() % 10 + 1;
}while(check(oldRandoms,x,get));
oldRandoms[x]=get; // backup the number
printf("random number is %d \n", get);
value = get;
for (loop = 0; loop < 1000; loop++)
{
if (value <= 1) { arr[loop] = 1; break; } //if value is 1 after dividing put 1 in array
if (value % 2 == 0) arr[loop] = 0;
else arr[loop] = 1;
value = value / 2;
}
for (loop1 = loop; loop1 > -1; loop1--)
printf("%d", arr[loop1]);
printf("\n");
}
}
int main() //8th task
{
int longNum, shortNum, tempNum[5], i;
printf("Please enter 2 numbers (5 digits and 1 digit, ex: 12345 and 5)\n");
scanf("%d%d", &longNum, &shortNum);
for (i = 4; i >= 0; i--)
{
if (longNum % 10 != shortNum)
{
tempNum[i] = longNum % 10;
longNum /= 10;
}
else tempNum[i] = ; // Delete the digit that == shortNum.
}
for (i = 0; i < 5; i++)
{
printf("%d", tempNum[i]);
}
printf("\n");
return 0;
}
This program check if longNum has shortNum in it and suppose to remove the number (and his array slot) from longNum.
I've tried couple of things to make it work with no success.
I'd like to know what is the best way to do it (im not sure what the 'else' should be).
It is possible to skip all shortNum digits in the parsing loop. One more variable is needed to track number of deleted digits:
int n = 5;
for (i = 4; i >= 0; i--)
{
int tmp = longNum % 10;
longNum /= 10;
if (tmp != shortNum)
tempNum[--n] = tmp;
}
// here n is number of deleted digits
for (i = n; i < 5; i++)
{
printf("%d", tempNum[i]);
}
So, actually elements are not deleted from array. They are not written to that array. It is also possible to reverse elements order, so the first array element will be meaningful. Now if some element is skipped the first element of tempNum contains junk.
you need to skip the value that you don't want, and not insert it at all to the array.
int len = 0;
for (i = 4; i >= 0; i--)
{
if (longNum % 10 != shortNum)
{
tempNum[len] = longNum % 10;
len++;
}
longNum /= 10;
}
for (i = 0; i < len; i++)
{
printf("%d", tempNum[i]);
}
else tempNum[i] = ; this part is very wrong. You have to assing something like else tempNum[i] = 0;. And you can't actually delete anything from these arrays - they are not dynamic. I suggest you read up on dynamic arrays.
I've created a solution to problem 4 on Project Euler.
However, what I find is that placing the print statement (that prints the answer) in different locations prints different answers. And for some reason, the highest value of result is 580085. Shouldn't it be 906609? Is there something wrong with my isPalindrome() method?
#include <stdio.h>
#include <stdbool.h>
int isPalindrome(int n);
//Find the largest palindrome made from the product of two 3-digit numbers.
int main(void)
{
int i = 0;
int j = 0;
int result = 0;
int palindrome = 0;
int max = 0;
//Each iteration of i will be multiplied from j:10-99
for(i = 100; i <= 999; i++)
{
for(j = 100; j <= 999; j++)
{
result = i * j;
if(isPalindrome(result) == 0)
{
//printf("Largest Palindrome: %d\n", max); //906609
//printf("Result: %d\n", result); //580085
if(result > max)
{
max = result;
//printf("Largest Palindrome: %d\n", max); //927340
}
printf("Largest Palindrome: %d\n", max); //906609
}
}
}
//printf("Largest Palindrome: %d\n", max); //998001
system("PAUSE");
return 0;
} //End of main
//Determines if number is a palindrome
int isPalindrome(int num)
{
int n = num;
int i = 0;
int j = 0;
int k = 0;
int count = 0;
int yes = 0;
//Determines the size of numArray
while(n/10 != 0)
{
n%10;
count++;
n = n/10;
}
int numArray[count];
//Fill numArray with each digit of num
for(i = 0; i <= count; i++)
{
numArray[i] = num%10;
//printf("%d\n", numArray[i]);
num = num/10;
}
//Determines if num is a Palindrome
while(numArray[k] == numArray[count])
{
k = k + 1;
count = count - 1;
yes++;
}
if(yes >= 3)
{
return 0;
}
}//End of Function
I remember doing that problem a while ago and I simply made a is_palindrome() function and brute-forced it. I started testing from 999*999 downwards.
My approach to detect a palindrome was rather different from yours. I would convert the given number to a string and compare the first char with the nth char, second with n-1 and so on.
It was quite simple (and might be inefficient too) but the answer would come up "instantly".
There is no problem in the code in finding the number.
According to your code fragment:
.
.
}
printf("Largest Palindrome: %d\n", max); //906609
}
}
}
//printf("Largest Palindrome: %d\n", max); //998001
system("PAUSE");
.
.
.
you get the result as soon as a palindrome number is found multiplying the number downwards.
You should store the palindrome in a variable max and let the code run further as there is a possibility of finding a greater palindrome further.
Note that for i=800,j=500, then i*j will be greater when compare with i=999,j=100.
Just understand the logic here.
A few issues in the isPalindrome function :
the first while loop doesn't count the number of digits in the number, but counts one less.
as a result, the numArray array is too small (assuming that your compiler supports creating the array like that to begin with)
the for loop is writing a value past the end of the array, at best overwriting some other (possibly important) memory location.
the second while loop has no properly defined end condition - it can happily compare values past the bounds of the array.
due to that, the value in yes is potentially incorrect, and so the result of the function is too.
you return nothing if the function does not detect a palindrome.
//Determines if number is a palindrome
bool isPalindrome(int num) // Change this to bool
{
int n = num;
int i = 0;
int j = 0;
int k = 0;
int count = 1; // Start counting at 1, to account for 1 digit numbers
int yes = 0;
//Determines the size of numArray
while(n/10 != 0)
{
// n%10; <-- What was that all about!
count++;
n = n/10;
}
int numArray[count];
//Fill numArray with each digit of num
for(i = 0; i < count; i++) // This will crash if you use index=count; Array indices go from 0 to Size-1
{
numArray[i] = num%10;
//printf("%d\n", numArray[i]);
num = num/10;
}
//Determines if num is a Palindrome
/*
while(numArray[k] == numArray[count-1]) // Again count-1 not count; This is really bad though what if you have 111111 or some number longer than 6. It might also go out of bounds
{
k = k + 1;
count = count - 1;
yes++;
}
*/
for(k = 1; k <= count; k++)
{
if(numArray[k-1] != numArray[count-k])
return false;
}
return true;
}//End of Function
That's all I could find.
You also need to change this
if(isPalindrome(result) == 0)
To
if(isPalindrome(result))
The Code's Output after making the modifications: Link
The correct printf is the one after the for,after you iterate through all possible values
You are using int to store the value of the palidrome but your result is bigger then 65536,
you should use unsigned
result = i * j;
this pice of code is wrong :
while(n/10 != 0) {
n%10;
count++;
n = n/10;
}
it should be:
while(n != 0) {
count++;
n = n/10;
}
As well as the changes that P.R sugested.
You could do something like this to find out if the number is palindrome:
int isPalindrom(unsigned nr) {
int i, len;
char str[10];
//convert number to string
sprintf(str, "%d", nr);
len = strlen(str);
//compare first half of the digits with the second half
// stop if you find two digits which are not equal
for(i = 0; i < len / 2 && str[i] == str[len - i - 1]; i++);
return i == len / 2;
}
I converted the number to String so I'd be able to go over the number as a char array:
private static boolean isPalindrom(long num) {
String numAsStr = String.valueOf(num);
char[] charArray = numAsStr.toCharArray();
int length = charArray.length;
for (int i = 0 ; i < length/2 ; ++i) {
if (charArray[i] != charArray[length - 1 - i]) return false;
}
return true;
}
I got correct answer for the problem, but I want to know is my coding style is good or bad from my solution. I need to know how can I improve my coding,if it is bad and more generic way.
#include<stdio.h>
#define MAX 999
#define START 100
int main()
{
int i,j,current,n,prev = 0;
for(i = START;i<=MAX;i++)
{
for(j=START;j<=MAX;j++)
{
current = j * i;
if(current > prev) /*check the current value so that if it is less need not go further*/
{
n = palindrome(current);
if (n == 1)
{
printf("The palindrome number is : %d\n",current);
prev = current; // previous value is updated if this the best possible value.
}
}
}
}
}
int palindrome(int num)
{
int a[6],temp;
temp = num;
/*We need a array to store each element*/
a[5] = temp % 10;
a[4] = (temp/10) %10;
a[3] = (temp/100) %10;
a[2] = (temp/1000) %10;
a[1] = (temp/10000) %10;
if(temp/100000 == 0)
{
a[0] = 0;
if(a[1] == a[5] && a[2] == a[4])
return 1;
}
else
{
a[0] = (temp/100000) %10;
if(a[0] == a[5] && a[1] == a[4] && a[2] == a[3])
return 1;
else
return 0;
}
}
No, the largest should be: 906609.
Here is my program:
def reverse_function(x):
return x[::-1]
def palindrome():
largest_num = max(i * x
for i in range(100, 1000)
for x in range(100, 1000)
if str(i * x) == reverse_function(str(i * x)))
return str(largest_num)
print(palindrome())