C++ uint64_t bitwise AND check for even number - c

I have the following code that simply checks if a uint64_t is even, I intended on using a bitwise AND operation to check but it doesn't seem to be working.
This is the code I thought would work first:
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++){
uint64_t s,d;
scanf("%llu %llu",&s,&d);
//try for x
uint64_t x;
bool stop = false;
x = s + d;
printf("%llu",x&1ULL); \\ This prints 0 when the number is even but
if(x&1ULL==0ULL){ \\ This check always returns false
printf("%llu",x);
x/= 2;
This code always prints out 0 or 1 if the the number is odd or even but the if statement always returns false. What am I doing wrong? Thanks

x&1ULL==0ULL is equivalent to x&(1ULL==0ULL). You need (x&1ULL)==0ULL.

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <stdint.h>
int main()
{
int n;
scanf_s("%d", &n);
for (int i = 0; i < n; i++) {
uint16_t s, d;
scanf_s("%llu %llu", &s, &d);
//try for x
uint16_t x;
bool stop = false;
x = s + d;
printf("%llu", x & 1ULL);
if ((x & 1ULL) == 0ULL) {
printf("%llu", x);
x /= 2;
}
}
return 0;
}
I think this should work anyway for me it works

Related

why is my function outputting incorrectly?

I created a factorial function and my output for integer b is incorrect when it is set at 5, any ideas as to why? b should be equal to the integer 120 and I am getting the number -95449088 after I compile and run it.
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i;
for(i=1; i < x; i++)
x *= i;
return x;
}
int main() {
int a=5, b;
b = factorial(a);
printf("%d\n", b);
}
Here you are using the same x value in the condition check of for-loop which is a mess up. Instead you can store the variable x to a variable temp and use this temp variable for checking the condition.
Please see below the corrected code
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i,temp=0;
temp = x; //store the x to temp
for(i=1; i < temp; i++){
x *= i;
}
return x;
}
int main() {
int a=5, b;
b = factorial(a);
printf("%d\n", b);
}
Other have explained that you should avoid mixing input and output variables. This is good advice, and as a beginner you should try to observe it.
But this is a special case, and here you can re-use the input value, provided you use a decreasing loop:
int factorial(int x)
{
int i;
for (i = x-1; i >1; i--)
x *= i;
return x;
}
It works because it implicitly initializes the return value with x and then multiplies it by all numbers below it, which is a possible definition for the factorial.

Algorithm to find and print figures that are common to two given long integers

Please help me with the appropriate C algorithm without using arrays.
Example:
Input
123456789
2037
Output
Common figures are 2, 3, 7.
My failed attempt:
long a, b, original_a, original_b;
int i, j, figure_a, figure_b;
printf("a=");
scanf_s("%li", &a);
printf("b=");
scanf_s("%li", &b);
original_a = a;
original_b = b;
for (i = 0; i <= 9; i++)
for (j = 0; j <= 9; j++){
a = original_a;
b = original_b;
while (a||b){
figure_a = a % 10;
figure_b = b % 10;
a /= 10;
b /= 10;
if (i == figure_a && j == figure_b && i == j)
printf("%d, ", i);
}
}
You can convert both the integers to strings and then compare each character of the first string with the second one to check whether any of them matches or not. I've used nested for loops for comparing.
I've used strings because comparing each character of two strings is a lot easier than comparing each digit of two integers.
#include <stdio.h>
int main()
{
long int a,b;
int i,j;
scanf("%ld %ld",&a,&b); //taking both inputs
char temp_a[50],temp_b[50];
sprintf(temp_a, "%ld", a); //converting the first integer to a string
sprintf(temp_b, "%ld", b); //converting the second integer to a string
int length_a=strlen(temp_a); //length of first string
int length_b=strlen(temp_b); //length of second string
// matching whether any character is in common using nested for-loops
// printing the character as soon as it matches
// if a character matches, the loop breaks.
for(i=0 ; i<length_a ; i++)
{
for(j=0 ; j<length_b ; j++)
{
if(temp_a[i]==temp_b[j])
{
printf("%c",temp_a[i]);
break;
}
}
}
}
This is a fun little problem.
I threw together a quick, simple solution:
#include <stdio.h>
int main(void)
{
int a, b;
int d[10]={0};
scanf("%d %d", &a, &b);
while(a)
{
d[a%10] = 1;
a /= 10;
}
while(b)
{
if (d[b%10]) d[b%10]=2;
b /= 10;
}
for(a=0;a<10;++a) if (d[a]==2) printf("%d ", a);
return 0;
}
Link to IDE One code
Here's a short version that does not use arrays:
#include <stdio.h>
int main(void)
{
int a, b, c;
scanf("%d %d", &a, &b);
while(a)
{
c = b;
while(c)
{
if (c%10 == a%10)
{
printf("%d ", c%10);
break;
}
c /= 10;
}
a /= 10;
}
return 0;
}
This version runs slower than my first one, and does not print out the numbers in ascending order.
May it helps:
#include <stdio.h>
int original_a, original_b, i;
short digit_a, digit_b, digit_common;
short find_digit(int num);
int main()
{
printf("Insert 2 numbers a and b\n");
scanf("%d %d", &original_a, &original_b);
digit_a = find_digit(original_a);
digit_b = find_digit(original_b);
digit_common = digit_a & digit_b;
printf("digit_common: %x\n", digit_common);
printf("Common digits of a and b\n");
for(i = 0; i < 10; i++){
if(digit_common & (1<<i)){
printf("%d",i);
}
}
return 0;
}
short find_digit(int num){
short result = 0;
while(num>0){
result |= (1 << (num%10));
num /= 10;
}
return result;
}

Calculating a Serie in C

This image is the task I should do:
Whatever I enter between -1 and 1, the outputs are always 1.0000 or 2.0000. How can I do solve this problem? Below I attached my code.
#include <stdio.h>
#include <math.h>
int main() {
int i;
float x;
float sum=0;
printf ("enter an x\n");
scanf ("%f",&x);
if ((x>-1)&&(x<1))
{
for (i=0;i<101;i++)
sum= sum + (pow(x,i));
}
printf ("result=%f",sum);
return 0;
}
if ((x>-1)&&(x<1))
With this case your code will work only if x is zero so try removing if statement and do mention what output you expect for given particular input, it will be bit more helpful to answer it.
Try this code:
#include <stdio.h>
#include <math.h>
int main() {
int i; float x;
float sum=0;
printf ("enter an x\n");
scanf ("%f",&x);
for (i=0 ;i<101; i++)
sum+= (pow(x,i));
printf ("result=%f",sum);
return 0;
}
Even upon using a type like double you haven't got enough numerical precision to sum all the powers up to 100.
Executing the following snippet, you'll notice that, while the correct (numerically speaking) result is evaluated, the loop stops way before the 100th iteration, typically at 16:
#include <stdio.h>
#include <math.h>
#include <float.h>
// Analytically calculates the limit for n -> inf of the series of powers
double sum_of_powers_limit(double x)
{
return 1.0 / (1.0 - x);
}
int main(void)
{
double x = 0.1;
const int N = 100;
double sum = 1.0;
for (int i = 1; i <= N; ++i)
{
double old_sum = sum;
sum = sum + pow(x,i);
if (old_sum == sum)
{
fprintf(stderr, "Numerical precision limit reached at i = %d\n", i);
break;
}
}
printf(" result = %.*e\n", DBL_DECIMAL_DIG, sum);
printf("expected = %.*e\n", DBL_DECIMAL_DIG, sum_of_powers_limit(x));
return 0;
}
Also note that a more efficient way to evaluate this kind of polynomials is the Horner's method:
// Evaluates the sum s(x) = 1 + x + x^2 + ... + x^n using Horner's method
// It stops when it cannot update the value anymore
double sum_of_powers(double x, int n)
{
double result = 1.0;
for (int i = 0; i < n; ++i)
{
double old_result = result;
result = 1.0 + x * result;
if (old_result == result)
{
fprintf(stderr, "Numerical precision limit reached at i = %d\n", i);
break;
}
}
return result;
}

Write a function to check if its parameter (positive integer) is a perfect square. Then apply this function to a vector of positive integers

I am new to functions and right now I am trying to understand them so please go easy on me if you see some "noob" mistakes.I would really appreciate some help with this program:
#include <stdio.h>
#include <stdlib.h>
int check(int a[],int n,int i )
{
int j;
for (j=0; j<n ; j++)
{
if(a[i]==j*j)
return 1;
else
return 0;
}
}
int main()
{
int n,a[100],i;
printf("\nThe size:\n");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("\na[%d]=",i);
scanf("%d",&a[i]);
if(check(a,n,i)==1)
printf("%d is a perfect square\n",a[i]);
else
printf("%d is not a perfect square\n",a[i]);
}
return 0;
}
I succeeded in making it run but something isn't right no matter the input (1,4,5,9...) it will always print:" is not a perfect square "
What you need is to pass only a number to the function instead. To do that, you can simply do:
int check(int value, int n)
{
for (int j=0; j<n ; j++)
if(value==j*j)
return 1;
return 0;
}
and call the function like this:
check(a[i], n)
Now, you are not passing the whole array, but only a number, i.e. the i-th number of it.
At this point, you have a function to check one number. Think what you need to do, to check a collection of numbers. How would you apply that check() to every number of your vector?
PS: An important and fundamental note is that you should indent your code, since it makes everything much more readable (for example, curly brackets get aligned).
Appendix:
You could make your initial function work like this:
int check(int a[],int n,int i )
{
int j;
for (j=0; j<n ; j++)
{
if(a[i]==j*j)
return 1;
}
return 0;
}
so that you don't stop looping over when the condition is not mean, but will continue checking the other entries as well.
However, I strongly recommend using my suggestion above.
Write a function to check if its parameter (positive integer) is a perfect square
What is needed is:
bool check_if_perfect_square(unsigned n);
Simple find the integer square root. Integer square root routines are not too hard to code. Maybe:
#include <stdbool.h>
// Square root of t round toward 0
unsigned uisqrt(unsigned t) {
unsigned s, b;
for (b = 0, s = t; b++, s >>= 1) {
;
}
s = 1u << (b >> 1);
if (b & 1) {
s += s >> 1;
}
do {
b = t / s;
s = (s + b) >> 1;
} while (b < s);
return s;
}
If you do not like that advanced approach, code could slowly iterate. No need to iterate to i<n, but to i <= n/i.
unsigned uisqrt(unsigned n) {
unsigned i = 0;
if (n > 0) {
for (i = 1; i <= n/i; i++) {
;
}
i--;
}
return i;
}
Then the check is easily
#include <stdbool.h>
bool check_if_perfect_square(unsigned n) {
unsigned sr = uisqrt(n);
return sr*sr == n);
}
Then apply this function to a vector of positive integers
Armed with a check_if_perfect_square(), simply iterate over the array.
#include <stddef.h>
#include <stdio.h>
void square_root_test_array(unsigned *a, size_t array_length) {
for (size_t i = 0; i<array_length; i++) {
if (check_if_perfect_square(a[i])) {
printf("%u is a perfect square\n",a[i]);
} else {
printf("%d is not a perfect square\n",a[i]);
}
}
}
Sample use
int main() {
printf("\nThe size:\n");
unsigned n = 0;
scanf("%u",&n);
unsigned a[n];
for(unsigned i=0; i<n; i++) {
printf("a[%u] = ",i);
scanf("%d",&a[i]);
}
// Now test array
square_root_test_array(a, n);
return 0;
}

The following program "Counting consecutive 1's of a binary no" shows different ans when input goes more than 8-digit value?

I have tried different inputs and when it exceeds a 7 or 8 digit value it just shows some wrong answers as outputs but it worked fine with most of my cases.
#include <stdio.h>
#include <stdlib.h>
int bin(unsigned long long int n){//gave function for binary convertion
if(n==0)
return 0;
else
return (n%2+10*bin(n/2));
}
int main()
{
unsigned long long int n,x;/*I even gave high digit data type*/
int i, v, count=0, max=0;
scanf("%llu",&n); /*if input is >8-digit output is wrong*/
x = bin(n);
v = floor(log10(x))+1; /*Its length*/
int a[v];
for(i = v-1; i >= 0; i--){ /*string it in array*/
a[i] = x%10;
x = x/10;
}
for(i = 0; i < v; i++){
if(a[i] == 0){
count = 0;}
else{
count++;}
if(max < count){
max = count;}
}
printf("%d",max);/*I gave 99999999 output is 8 but its shows 9*/
}
Your program has a number of problems. Here is one example:
int bin(unsigned long long int n){
^^^
The function returns an int so the calculation will overflow for even small numbers:
printf("%d\n", bin(1023)); // will print 1111111111 (fine)
printf("%d\n", bin(1024)); // will/may print 1410065408 (ups - very bad)
Even if you change to
unsigned long long int bin(unsigned long long int n){
overflow will happen soon.
In I'll recommend that you look directly into the binary pattern of the number using the & operator.
I'll not solve the complete task for you but here is some code that may help you.
#include <stdio.h>
#include <stdlib.h>
int main()
{
size_t t = 1;
size_t limit;
size_t n;
if (scanf("%zu", &n) != 1)
{
printf("Illegal input\n");
exit(1);
}
limit = 8 * sizeof n; // Assume 8 bit chars
for (size_t i = 0; i < limit; ++i)
{
if (n & t)
{
printf("Bit %zu is 1\n", i);
}
else
{
printf("Bit %zu is 0\n", i);
}
t = t << 1;
}
return 0;
}

Resources