i'm trying to write a code which can convert 2 decimal numbers 0 to 1 into binary, then adding them and printing the binary values for the 2 initial numbers AND the final sum. It compiles with no problems however when I run it crashes right after it converts and prints num1 and num2 (the initial numbers), I can't seem to find the problem.
the general formula for binary addition is:
*ith bit of sum = ith bit of binary1 + ith bit of binary2 + carry factor (0 or 1)
if sum > 1, subtract 2 and add 1 to the next operation (which is the carry factor i mentions earlier)
Below is the code
#include <stdio.h>
// Converting decimal number to a binary number
void convertDecToBin(double num, int len, int binary[]) {
// this function STORES conversion result in binary[]
double tmp = num;
binary[0] = 0;
for (int i = 0; i < len; i++) {
tmp *= 2;
binary[i + 1] = tmp >= 1;
if (tmp >= 1) {
tmp -= 1;
}
}
}
// Binary number addition
void addTwoBinary(int binary1[], int binary2[], int sum[]) {
int tmp;
int carry;
for (unsigned int i = 20; i >= 0; i--) {
if (i == 20 || tmp <= 1) {
carry = 0;
}
else if (tmp > 1) {
carry = 1;
}
sum[i] = binary1[i] + binary2[i] + carry;
tmp = sum[i];
if (sum[i] > 1) {
sum[i]-=2;
}
}
}
//Printing the numbers
void PrintBinary(int binary[], int len) {
for (unsigned int i = 0; i < len; i++) {
printf("%d", binary[i]);
}
}
int main(void) {
double num1, num2;
int binary1[30], binary2[30], sum[30];
scanf("%lf", &num1);
scanf("%lf", &num2);
convertDecToBin(num1, 30, binary1);
convertDecToBin(num2, 30, binary2);
printf("num1 is ");
PrintBinary(binary1, 21);
printf("\nnum2 is ");
PrintBinary(binary2, 21);
addTwoBinary(binary1, binary2, sum);
printf("\nsum is ");
PrintBinary(sum, 21);
return 0;
}
I was trying to solve Project Euler question 16 using c. I did not use bignnum libraries. The question asks 2^1000. I decided to store every digit of that number in an array.
For Example: 45 means arr[0]=4, arr[1]=5;
The problem is definitely i the function int multi.
#include<stdio.h>
#include<conio.h>
int multi(int *base, int k);// does the multiplication of array term by 2
void switcher();//switches every term when the fore mostvalue is >10
int finder();// finds the array address of last value
int arr[1000];
int summer();//sums all values of the array
int main()
{
arr[1000] = { 0 };
arr[0] = 1;
int i, j, sum, k, p;
for (i = 0; i < 1000; i++)
{
j = 0;
k = finder();
p = multi(arr + k, j);
}
sum = summer();
printf("sum of digits of 2^1000 is %d", sum);
_getch();
}
int multi(int *base, int k)
{
int p;
if (base == arr)
{
*base = *base - 1;
*base = *base + k;
if (*base > 10)
{
*base = *base - 10;
switcher();
}
return 0;
}
*base = *base * 2;
*base = *base + k;
if (*base > 10)
{
*base = *base - 10;
p = multi(base - 1, 1);
}
else
{
p = multi(base - 1, 0);
}
}
void switcher()
{
int j;
for (j = 0;; j++)
{
if (arr[j] == 0)
{
break;
}
}
j--;
for (; j > 0; j--)
{
arr[j + 1] = arr[j];
}
arr[0] = 1;
}
int finder()
{
int j;
for (j = 0;; j++)
{
if (arr[j] == 0)
{
break;
}
}
return --j;
}
int summer()
{
int summ, i;
summ = 0;
for (i = 0; i<1000; i++)
{
summ = summ + arr[i];
if (arr[i] == 0)
break;
}
return summ;
}
It compiles but during runtime it shows Access Write Violation, base was ......
Please explain this error and how to resolve it ?
Array is of 100 Bytes but you are looping for 1000. Also in function Finder() , you do not have a limit on variable j so your array size is going beyond 100 bytes.
Also use memset to assign array variables to 0.
As said in the comments, 2^1000 has 302 decimal digits.
You're going far outside your array.
But your code is very complicated because you store the digits with the most significant one first.
Since you're only interested in the digits and not the order in which they would be written, you can store the number "in reverse", with the least significant digit first.
This makes the code much simpler, as you can loop "forwards" and no longer need to shuffle array elements around.
Using -1 as "end of number" marker, it might look like this:
void twice(int* digits)
{
int i = 0;
int carry = 0;
while (digits[i] >= 0)
{
digits[i] *= 2;
digits[i] += carry;
if (digits[i] >= 10)
{
carry = 1;
digits[i] -= 10;
}
else
{
carry = 0;
}
i++;
}
if (carry)
{
digits[i] = 1;
digits[i+1] = -1;
}
}
int main()
{
int digits[302] = {1, -1}; /* Start with 1 */
twice(digits); /* digits is now { 2, -1 } */
return 0;
}
#include <stdio.h>
#include <math.h>
int prime (long n);
long reverse(long n);
int main(void)
{
long n;
long i, j;
puts("Enter n dight number, and we will help you find symmetrical prime number");
scanf("%ld", &n);
for (i = 11; i < (pow(10, n) - 1); i+= 2)
{
if (prime(i))
{
j = reverse(i);
if (i == j)
{
printf("%ld\n", i);
}
}
}
}
int prime (long n) //estimate whether the number n is primer number
{
int status = 0;
int j;
//1 is prime, 0 is not
if (n % 2 == 0 || n == 3)
{
if (n == 2)
status = 1;
if (n == 3)
status = 1;
else
{
n++;
status = 0;
}
}
else
{
j = 3;
while (j <= sqrt(n))
{
if (n % j == 0)
{
status = 0;
break;
}
else
status = 1;
j+= 2;
}
}
return status;
}
long reverse(long n) //reverse a number
{
int i, j, x;
long k, sum;
int digit = 0;
int ar[1000];
while (n > 0)
{
k = n;
n = n / 10;
x = (k - n*10);
digit++;
ar[digit] = x;
}
for (i = 1,j = digit - 1; i <= digit; i++, j--)
{
sum += ar[i] * pow(10, j)
}
return sum;
}
I build a reverse function in order to reverse numbers, for example, 214, to 412.
This function works fine in individual number, for instance, I type reverse(214), it return 412, which is good. But when I combine reverse() function with for loop, this function can not work... it produces some strange number...
so How can I fix this problem?
The reverse function is extremely complicated. The better way to go about it would be:
long reverse (long n)
{
long result = 0;
while (n != 0)
{
result *= 10;
result += n % 10;
n /= 10;
}
return result;
}
I think the problem in your code is that in the following segment
digit++;
ar[digit] = x;
you first increment the position then assign to it, thus leaving ar[0] unintialized.
How can I fix this problem?
You need to initialize sum
long k, sum = 0;
^
See the code from #Armen Tsirunyan for a simpler approach.
I would like to know how I can find the length of an integer in C.
For instance:
1 => 1
25 => 2
12512 => 5
0 => 1
and so on.
How can I do this in C?
C:
You could take the base-10 log of the absolute value of the number, round it down, and add one. This works for positive and negative numbers that aren't 0, and avoids having to use any string conversion functions.
The log10, abs, and floor functions are provided by math.h. For example:
int nDigits = floor(log10(abs(the_integer))) + 1;
You should wrap this in a clause ensuring that the_integer != 0, since log10(0) returns -HUGE_VAL according to man 3 log.
Additionally, you may want to add one to the final result if the input is negative, if you're interested in the length of the number including its negative sign.
Java:
int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;
N.B. The floating-point nature of the calculations involved in this method may cause it to be slower than a more direct approach. See the comments for Kangkan's answer for some discussion of efficiency.
If you're interested in a fast and very simple solution, the following might be quickest (this depends on the probability distribution of the numbers in question):
int lenHelper(unsigned x) {
if (x >= 1000000000) return 10;
if (x >= 100000000) return 9;
if (x >= 10000000) return 8;
if (x >= 1000000) return 7;
if (x >= 100000) return 6;
if (x >= 10000) return 5;
if (x >= 1000) return 4;
if (x >= 100) return 3;
if (x >= 10) return 2;
return 1;
}
int printLen(int x) {
return x < 0 ? lenHelper(-x) + 1 : lenHelper(x);
}
While it might not win prizes for the most ingenious solution, it's trivial to understand and also trivial to execute - so it's fast.
On a Q6600 using MSC I benchmarked this with the following loop:
int res = 0;
for(int i = -2000000000; i < 2000000000; i += 200) res += printLen(i);
This solution takes 0.062s, the second-fastest solution by Pete Kirkham using a smart-logarithm approach takes 0.115s - almost twice as long. However, for numbers around 10000 and below, the smart-log is faster.
At the expense of some clarity, you can more reliably beat smart-log (at least, on a Q6600):
int lenHelper(unsigned x) {
// this is either a fun exercise in optimization
// or it's extremely premature optimization.
if(x >= 100000) {
if(x >= 10000000) {
if(x >= 1000000000) return 10;
if(x >= 100000000) return 9;
return 8;
}
if(x >= 1000000) return 7;
return 6;
} else {
if(x >= 1000) {
if(x >= 10000) return 5;
return 4;
} else {
if(x >= 100) return 3;
if(x >= 10) return 2;
return 1;
}
}
}
This solution is still 0.062s on large numbers, and degrades to around 0.09s for smaller numbers - faster in both cases than the smart-log approach. (gcc makes faster code; 0.052 for this solution and 0.09s for the smart-log approach).
int get_int_len (int value){
int l=1;
while(value>9){ l++; value/=10; }
return l;
}
and second one will work for negative numbers too:
int get_int_len_with_negative_too (int value){
int l=!value;
while(value){ l++; value/=10; }
return l;
}
You can write a function like this:
unsigned numDigits(const unsigned n) {
if (n < 10) return 1;
return 1 + numDigits(n / 10);
}
length of n:
length = ( i==0 ) ? 1 : (int)log10(n)+1;
The number of digits of an integer x is equal to 1 + log10(x). So you can do this:
#include <math.h>
#include <stdio.h>
int main()
{
int x;
scanf("%d", &x);
printf("x has %d digits\n", 1 + (int)log10(x));
}
Or you can run a loop to count the digits yourself: do integer division by 10 until the number is 0:
int numDigits = 0;
do
{
++numDigits;
x = x / 10;
} while ( x );
You have to be a bit careful to return 1 if the integer is 0 in the first solution and you might also want to treat negative integers (work with -x if x < 0).
A correct snprintf implementation:
int count = snprintf(NULL, 0, "%i", x);
The most efficient way could possibly be to use a fast logarithm based approach, similar to those used to determine the highest bit set in an integer.
size_t printed_length ( int32_t x )
{
size_t count = x < 0 ? 2 : 1;
if ( x < 0 ) x = -x;
if ( x >= 100000000 ) {
count += 8;
x /= 100000000;
}
if ( x >= 10000 ) {
count += 4;
x /= 10000;
}
if ( x >= 100 ) {
count += 2;
x /= 100;
}
if ( x >= 10 )
++count;
return count;
}
This (possibly premature) optimisation takes 0.65s for 20 million calls on my netbook; iterative division like zed_0xff has takes 1.6s, recursive division like Kangkan takes 1.8s, and using floating point functions (Jordan Lewis' code) takes a whopping 6.6s. Using snprintf takes 11.5s, but will give you the size that snprintf requires for any format, not just integers. Jordan reports that the ordering of the timings are not maintained on his processor, which does floating point faster than mine.
The easiest is probably to ask snprintf for the printed length:
#include <stdio.h>
size_t printed_length ( int x )
{
return snprintf ( NULL, 0, "%d", x );
}
int main ()
{
int x[] = { 1, 25, 12512, 0, -15 };
for ( int i = 0; i < sizeof ( x ) / sizeof ( x[0] ); ++i )
printf ( "%d -> %d\n", x[i], printed_length ( x[i] ) );
return 0;
}
Yes, using sprintf.
int num;
scanf("%d",&num);
char testing[100];
sprintf(testing,"%d",num);
int length = strlen(testing);
Alternatively, you can do this mathematically using the log10 function.
int num;
scanf("%d",&num);
int length;
if (num == 0) {
length = 1;
} else {
length = log10(fabs(num)) + 1;
if (num < 0) length++;
}
int digits=1;
while (x>=10){
x/=10;
digits++;
}
return digits;
sprintf(s, "%d", n);
length_of_int = strlen(s);
You may use this -
(data_type)log10(variable_name)+1
ex:
len = (int)log10(number)+1;
In this problem , i've used some arithmetic solution . Thanks :)
int main(void)
{
int n, x = 10, i = 1;
scanf("%d", &n);
while(n / x > 0)
{
x*=10;
i++;
}
printf("the number contains %d digits\n", i);
return 0;
}
Quite simple
int main() {
int num = 123;
char buf[50];
// convert 123 to string [buf]
itoa(num, buf, 10);
// print our string
printf("%s\n", strlen (buf));
return 0;
}
keep dividing by ten until you get zero, then just output the number of divisions.
int intLen(int x)
{
if(!x) return 1;
int i;
for(i=0; x!=0; ++i)
{
x /= 10;
}
return i;
}
This goes for both negative and positive intigers
int get_len(int n)
{
if(n == 0)
return 1;
if(n < 0)
{
n = n * (-1); // if negative
}
return log10(n) + 1;
}
Same logic goes for loop
int get_len(int n)
{
if(n == 0)
return 1;
int len = 0;
if(n < 0)
n = n * (-1);
while(n > 1)
{
n /= 10;
len++;
}
return len;
}
Why don't you cast your integer to String and get length like this :
int data = 123;
int data_len = String(data).length();
For simple programs...
int num = 456, length=0 // or read value from the user to num
while(num>0){
num=num/10;
length++;
}
Use another variable to retain the initial num value.
In my opinion the shortest and easiest solution would be:
int length , n;
printf("Enter a number: ");
scanf("%d", &n);
length = 0;
while (n > 0) {
n = n / 10;
length++;
}
printf("Length of the number: %d", length);
My way:
Divide as long as number is no more divisible by 10:
u8 NumberOfDigits(u32 number)
{
u8 i = 1;
while (number /= 10) i++;
return i;
}
I don't know how fast is it in compared with other propositions..
int intlen(int integer){
int a;
for(a = 1; integer /= 10; a++);
return a;
}
A more verbose way would be to use this function.
int length(int n)
{
bool stop;
int nDigits = 0;
int dividend = 1;
do
{
stop = false;
if (n > dividend)
{
nDigits = nDigits + 1;
dividend = dividend * 10;
}
else {
stop = true;
}
}
while (stop == false);
return nDigits;
}
int returnIntLength(int value){
int counter = 0;
if(value < 0)
{
counter++;
value = -value;
}
else if(value == 0)
return 1;
while(value > 0){
value /= 10;
counter++;
}
return counter;
}
I think this method is well suited for this task:
value and answers:
-50 -> 3 //it will count - as one character as well if you dont want to count
minus then remove counter++ from 5th line.
566666 -> 6
0 -> 1
505 -> 3
Solution
Use the limit where the integer length changes, in the case of the decimal it is a power of 10, and thus use a counter for each verification that the specified integer has not exceeded the limit.
With the math.h dependency:
#include <math.h>
int count_digits_of_integer(unsigned int integer) {
int count = 1;
while(1) {
int limit = pow(10, count);
if(integer < limit) break;
count++;
}
return count;
}
Without dependency:
int int_pow(int base, int exponent) {
int potency = base;
for(int i = 1; i < exponent; i++) potency *= base;
return potency;
}
int count_digits_of_integer(unsigned int integer) {
int count = 1;
while(1) {
int limit = int_pow(10, count);
if(integer < limit) break;
count++;
}
return count;
}
Implementation
#include <stdio.h>
// Copy and paste the solution code here
int main() {
printf("%i -> (%i digits)\n", 0, count_digits_of_integer(0));
printf("%i -> (%i digits)\n", 12, count_digits_of_integer(12));
printf("%i -> (%i digits)\n", 34569, count_digits_of_integer(34569));
printf("%i -> (%i digits)\n", 1234, count_digits_of_integer(1234));
printf("%i -> (%i digits)\n", 3980000, count_digits_of_integer(3980000));
printf("%i -> (%i digits)\n", 100, count_digits_of_integer(100));
printf("%i -> (%i digits)\n", 9, count_digits_of_integer(9));
printf("%i -> (%i digits)\n", 385784, count_digits_of_integer(385784));
return 0;
}
Output:
0 -> (1 digits)
12 -> (2 digits)
34569 -> (5 digits)
1234 -> (4 digits)
3980000 -> (7 digits)
100 -> (3 digits)
9 -> (1 digits)
385784 -> (6 digits)
Hmm, maybe like this...?
#define _LEN(x) (sizeof(#x)/sizeof(char)-1)
You can also use this function to find the length of an integer:
int countlength(int number)
{
static int count = 0;
if (number > 0)
{
count++;
number /= 10;
countlength(number);
}
return count;
}
I think I got the most efficient way to find the length of an integer
its a very simple and elegant way
here it is:
int PEMath::LengthOfNum(int Num)
{
int count = 1; //count starts at one because its the minumum amount of digits posible
if (Num < 0)
{
Num *= (-1);
}
for(int i = 10; i <= Num; i*=10)
{
count++;
}
return count;
// this loop will loop until the number "i" is bigger then "Num"
// if "i" is less then "Num" multiply "i" by 10 and increase count
// when the loop ends the number of count is the length of "Num".
}
int main(void){
unsigned int n, size=0;
printf("get the int:");
scanf("%u",&n);
/*the magic*/
for(int i = 1; n >= i; i*=10){
size++;
}
printf("the value is: %u \n", n);
printf("the size is: %u \n", size);
return 0;
}
#include <stdio.h>
int main(void){
int c = 12388884;
printf("length of integer is: %d",printf("%d",c));
return 0;
}