I get some homework, but i stack in it. Maybe you can help me. Task below.
Read the keyboard integer in the decimal system and establishment of a new system of numbers.
Output in the console number written in the new notation.
I made for 2 to 10 systems only and i can't make from 10 to 36. I tried to make in second loop something like this:
if ( result > 9 ) {
printf("%c", 55+number);
} else {
printf("%d", result);
}
my code:
#include <stdio.h>
int main() {
int number, base;
int i, result;
scanf("%d %d", &number, &base);
if ( number < base ) {
printf("%d\n", number);
} else {
for ( i = base; i <= number / base; i *= base );
for ( int j = i; j >= base; j /= base ) {
result = number / j;
printf("%d", result);
number = number % j;
}
printf("%d\n", number%base);
}
return 0;
}
else condition needs some changes:
1. value to digit conversion needs to apply to the inner loop and to the final printf("%d\n", number % base). Instead of adding in both places, simply make your loop run to j > 0, rather than j >= base and only use the last printf() for \n.
2. Rather than using a magic number 55 use result - 10 + 'A'. It easier to understand and does not depend on ASCII - (does depend on A, B, C ... being consecutive).
3. The rest is OK.
[edit]
#nos pointed out problem with if() condition.
So remove if ( number < base ) { ... else { and change for (i = base; to for (i = 1; making an even more simple solution.
// } else {
for (i = 1; i <= number / base; i *= base)
;
int j;
// for (j = i; j >= base; j /= base) {
for (j = i; j > 0; j /= base) {
result = number / j;
#if 1
if (result > 9) {
// printf("%c", 55 + result);
printf("%c", result - 10 + 'A');
} else {
printf("%d", result);
}
#else
printf("%d", result);
#endif
number = number % j;
}
printf("\n");
// }
int number, base;
scanf("%d %d", &number, &base);
int divisor = base;
while (divisor <= number)
divisor *= base;
while (divisor != 1) {
divisor /= base;
int digit = number / divisor;
number -= digit * divisor;
printf("%c", digit <= 9 ? digit + '0' : digit + 'A' - 10);
}
printf("\n");
return 0;
Caveat: Undefined behavior for numbers greater than ~200000000.
You're on the right track and are very close to the answer. Your program is printing the resulting digits in two places.
I suggest making a single function to output the digits and using it in both places:
void print_digit(int number) {
// your code here
}
You can add characters and integers, so try something more like:
'A' + // some int value
On the other hand, should one like a solution that does not under/overflow, handles all INT_MIN to INT_MAX, no UB, only enter INT_MIN <= number <= INT_MAX, 2 <= base <= 36, and you don't mind recursion.
#include <stdio.h>
#include <stdlib.h>
void print_digit(int x, int base) {
int quot, rem;
quot = x/base;
if (quot) {
print_digit(quot, base);
}
rem = abs(x%base);
if (rem > 9) {
printf("%c", rem - 10 + 'A');
} else {
printf("%d", rem);
}
}
int main() {
int number, base;
scanf("%d %d", &number, &base);
if (number < 0) {
printf("-");
}
print_digit(number, base);
printf("\n");
return 0;
}
Related
I can't figure out how to print next ten Perfect numbers.
Here's what I have got so far:
#include <stdio.h>
int main() {
int n, c = 1, d = 2, sum = 1;
printf("Enter any number \n");
scanf("%d", &n);
printf("The perfect numbers are:");
while(c <= 10) {
sum = 1;
d = 2;
while(d <= n / 2) { //perfect no
if(n % d == 0) {
sum = sum + d;
}
d++;
}
if(sum == n) {
printf("%d\n", n);
}
c++;
}
return 0;
}
The output I am currently receiving:
input: 2 (say)
output: 6
What I want:
input: 2
output:
6
28
496
8128
33550336
858986905
137438691328
2305843008139952128
2658455991569831744654692615953842176
191561942608236107294793378084303638130997321548169216
I have just started coding. Any help will be appreciated.
The integer overflow issue mentioned by several folks is significant, but secondary. Even if we fix your broken logic, and adjust it to handle larger, fixed sized integers:
#include <stdio.h>
int main() {
unsigned long long number;
printf("Enter any number \n");
scanf("%llu", &number);
printf("The perfect numbers are:\n");
int total = 0;
while (total < 10) {
unsigned long long sum = 1, divisor = 2;
while (divisor <= number / 2) {
if (number % divisor == 0) {
sum += divisor;
}
divisor++;
}
if (sum == number) {
printf("%llu\n", number);
total++;
}
number += 1;
}
return 0;
}
You still wouldn't get past the first four perfect numbers in any reasonable amount of time:
> ./a.out
Enter any number
2
The perfect numbers are:
6
28
496
8128
The primary issue is you're using a bad algorithm. Read about Mersenne primes, and their relationship to perfect numbers, as well as the Lucas-Lehmer test. This approach takes more thought, but surprisingly, not much more code. And will produce more results faster (though eventually bog down as well.)
You have to put the counter after you find a perfect number, so increasing c must happen in the if statement that checks the perfect number, like this:
if(sum==n){
printf("%d",n);
c++;
}
After this you need to increase the number, called n, like this:
n++;
and based on the numbers, #Jonathan Leffler is right, you should use proper variables.
Research, divide and conquer
Perfect numbers are of the form 2p − 1 * (2p − 1).
Code will need extended precision to form 191561942608236107294793378084303638130997321548169216
Increase efficiency
Iterating to <= n / 2 takes far too long. Iterate up to <= n / d
// while(d <= n / 2) {
while(d <= n / d) {
Sample improved code:
bool isprime(unsigned long long x) {
if (x > 3) {
if (x % 2 == 0) {
return false;
}
for (unsigned long t = 3; t <= x / t; t += 2) {
if (x % t == 0) {
return false;
}
}
return true;
}
return x >= 2;
}
Advanced: See Lucas–Lehmer primality test for quick prime test of Mersenne numbers
The below code works for all but the 10th perfect number as code must test for isprime(267 - 1) and I should leave something for OP to do.
static void buff_mul(char *buff, unsigned power_of_2) {
unsigned long long m = 1ull << power_of_2;
size_t len = strlen(buff);
unsigned long long carry = 0;
for (size_t i = len; i > 0;) {
i--;
unsigned long long sum = (buff[i] - '0') * m + carry;
buff[i] = sum % 10 + '0';
carry = sum / 10;
}
while (carry) {
memmove(buff + 1, buff, ++len);
buff[0] = carry % 10 + '0';
carry /= 10;
}
}
void print_perfext(unsigned p) {
// 2**(p-1) * (2**p - 1)
assert(p > 1 && p <= 164);
char buff[200] = "1";
buff_mul(buff, p);
buff[strlen(buff) - 1]--; // Decrement, take advantage that the LSDigit is never 0
buff_mul(buff, p - 1);
puts(buff);
fflush(stdout);
}
//unsigned next_prime(unsigned first_numeber_to_test_if_prime) {
#include <stdio.h>
int main() {
unsigned p = 0;
for (unsigned i = 0; i < 9; i++) {
// If p prime && 2**p − 1 is prime, then 2**(p − 1) * (2**p − 1) is a perfect number.
while (!isprime(p) || !isprime((1uLL << p) - 1))
p++;
printf("%2u ", p);
print_perfext(p);
p++;
}
return 0;
}
Output
2 6
3 28
5 496
7 8128
13 33550336
17 8589869056
19 137438691328
31 2305843008139952128
61 2658455991569831744654692615953842176
From output you wrote I belive that u want to show 10 first perfect numbers
Now u are only showing 6 because u show them from 1 to 10. In this range there is only 6.
I wrote sth like this:
#include <stdio.h>
int isperfect(int input) {
int sum = 0, value = input / 2;
do {
if (input % value == 0) sum += value;
value--;
} while (value);
if (input == sum) return 1;
else return 0;
}
int main() {
int i;
int count;
for (i = 2, count = 0; count < 4; i++) {
if (isperfect(i) == 1) {
count++;
printf("%d\n", i);
}
}
return 0;
}
But I don't recomend counting more than 4 because its gonna take too much time
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 need to add the digits on the even and odd places in an integer. Say, Let number = 1234567. Sum of even place digits = 2+4+6 = 12 Sum of odd place digits = 1+3+5+7 = 16
The code I currently have is:
int returnsum(int num) {
while (num) {
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
while (sum) {
a = sum % 10;
arr[i] = a:
sum = sum / 10;
i++;
}
for (i = 0; a[i]; i += 2) {
summ = summ + a[i];
}
return summ;
}
void main() {
int n, m, oddSum = 0, evenSum = 0;
printf("Please insert the number for the program:");
scanf("%d", & n);
while (n != 0) {
oddSum += n % 10;
n /= 10;
evenSum += n % 10;
n /= 10;
}
printf("Sum of digits in even places:%d\n", evenSum);
printf("Sum of digits in odd places:%d\n", oddSum);
}
Here is a solution for your problem:
void main()
{
int n,m,oddSum=0,evenSum=0;
printf("Please insert the number for the program:");
scanf("%d",&n);
int flag=0;
int counter=1;
while (n!=0) {
if(counter%2==0)
{
evenSum += n % 10;
n /= 10;
}
else
{
oddSum += n % 10;
n /= 10;
}
counter++;
}
if(counter%2==0)
{
int temp=oddSum;
oddSum=evenSum;
evenSum=temp;
}
printf("Sum of digits in even places:%d\n",evenSum);
printf("Sum of digits in odd places:%d\n",oddSum);
}
Okay, let's first assume the number has an even number of digits, so that the second-last and last are at odd and even positions respectively.
Then, the last digit can be retrieved with number % 10 and the second last with (number / 10) % 10.
So, knowing that, you can simply loop over the number, adding those values and dividing by a hundred until you get a number less than ten.
If that number is zero, then your assumption about the original having an even number of digits was correct and you can exit.
If it's a non-zero (1..9), then your assumption was wrong, you should swap the even and odd sums to date then add the final digit to the odd sum.
The pseudo-code goes something like this:
def getEvenOdd (num):
even = 0
odd = 0
while num > 9:
even = even + (num % 10)
odd = odd + ((num / 10) % 10)
num = num / 100
if num > 0:
temp = even
even = odd
odd = temp
odd = odd + num
return (even,odd)
print getEvenOdd(1234567)
And the output of that would be something like (12,16).
And it's no accident that pseudo-code looks like beginner's Python, since that language is the perfect pseudo-code language, provided you don't mess about with the more complex corners of it.
Check the below code:
#include <stdio.h>
int main(void){
char p[20];
int i=0,even=0,odd=0,n;
scanf("%d",&n);
sprintf(p,"%d",n);
while(p[i] != '\0')
{
if(i%2 == 0)
odd+= (p[i] - '0');
else
even+= (p[i] - '0');
i++;
}
printf("%d\n",even);
printf("%d\n",odd);
return 0;
}
To sum every other digit, simply divide by 100 in each iteration:
int sumodd(int num) {
int sum = 0, rem;
while(num) {
rem=num%10;
sum=sum+rem;
num=num/100);
}
return sum;
}
Since we already have a function that can sum every other digit, we can re-use it:
int sumeven(int num) {
return sumodd(num/10);
}
My five cents.:)
#include <stdio.h>
typedef struct pair
{
unsigned int odd;
unsigned int even;
} pair_t;
pair_t GetSums( unsigned int x )
{
const unsigned int Base = 10;
pair_t sums = { 0u, 0u };
size_t n = 0;
do
{
if ( ++n & 1 ) sums.odd += x % Base;
else sums.even += x % Base;
} while ( x /= Base );
if ( ( n & 1 ) == 0 )
{
unsigned int tmp = sums.odd;
sums.odd = sums.even;
sums.even = tmp;
}
return sums;
}
int main(void)
{
while ( 1 )
{
unsigned int x;
pair_t sums;
printf( "\nEnter a non-negative number (0 - exit): " );
if ( scanf( "%u", &x ) != 1 || x == 0 ) break;
sums = GetSums( x );
printf( "\nSum of digits in odd positions is %u\n", sums.odd );
printf( "Sum of digits in even positions is %u\n", sums.even );
}
return 0;
}
The output might look like
Enter a non-negative number (0 - exit): 1234567
Sum of digits in odd positions is 16
Sum of digits in even positions is 12
Enter a non-negative number (0 - exit): 123456
Sum of digits in odd positions is 9
Sum of digits in even positions is 12
Enter a non-negative number (0 - exit): 0
Write a program that will find the largest number smaller than N that is totally different from a given number X. One number is totally different from other only if it doesn't contain any of the digits from the other number. N and X are read from standard input. The problem should be solved without the use of arrays.
Example Input 1: 400 897
Example Output 1: 366
Example Input 2: 1000 1236498
Example Output 2:777
No it's not homework, it was on one of the midterms and it's been killing me. I though about taking the first numbers last digit with %10 then taking the second numbers digit with %10 comparing them but...I just can't get it to work...I ended up with an endless loop...I just don't understand how to get every digit of the numbers and compare them to the other number.
#include <stdio.h>
int main () {
int N, X, num_N, num_X, i, lastDigit_N, lastDigit_X, flag, smaller_than_N;
scanf("%d%d", &N, &X);
smaller_than_N = N - 1;
for (i = smaller_than_N; i > 0; i--) {
num_N = i;
num_X = X;
flag = 0;
while (num_N > 0) {
lastDigit_N = num_N % 10;
while (num_X > 0) {
lastDigit_X = num_X % 10;
if (lastDigit_N == lastDigit_X) {
break;
}
else {
flag = 1;
}
num_X /= 10;
}
num_N /= 10;
}
if(flag) {
printf("%d", i);
break;
}
}
return 0;
}
You could build a bitmask for your numbers showing the digits which are contained.
uint16_t num2bitmask(int number)
{
uint16_t result = 0;
while (number) {
int digit = number % 10;
number /= 10;
result |= (1 << digit);
}
return result;
}
With this function, you can create your bitmask for X and then iterate from N-1 down to 1 until you find a value which doesn't have any bits in common with the other value.
If you have a number with digits d_1, d_2, ..., d_n, and you're allowed to use digits in the set D, then possible solutions look like:
d_1, ..., d_{i-1}, max(d in D | d < d_i), max(d in D), ..., max(d in D).
That is, the digits are the same up to some point, then the next digit is as large as possible while being below the input digit, then the rest are just as large as possible.
Not all these "solutions" will be valid, but if you iterate through them in reverse order (there's exactly n for an input number of size n), the first valid one you find is the answer.
Some code, including tests:
#include <stdio.h>
int digit_length(int a) {
int r = 0;
while (a) {
a /= 10;
r += 1;
}
return r;
}
int get_digit(int a, int k) {
while (k--) a /= 10;
return a % 10;
}
int largest_different(int a, int b) {
int lena = digit_length(a);
int invalid = b ? 0 : 1;
for (; b; b /= 10) invalid |= 1 << (b % 10);
int max_valid = 9;
while (max_valid >= 0 && (invalid & (1 << max_valid)))
max_valid--;
if (max_valid == -1) return -1;
for (int i = 0; i < lena; i++) {
int d = get_digit(a, i) - 1;
while (d >= 0 && (invalid & (1 << d)))d--;
if (d < 0) continue;
int solution = 0;
for (int k = lena - 1; k >= 0; k--) {
solution *= 10;
solution += (k < i ? max_valid : k > i ? get_digit(a, k) : d);
}
return solution;
}
return -1;
}
int main(int argc, char *argv[]) {
struct {int n; int x; int want;} examples[] = {
{400, 897, 366},
{1000, 1236498, 777},
{998, 123, 997},
};
int error = 0;
for (int i = 0; i < sizeof(examples) / sizeof(*examples); i++) {
int got = largest_different(examples[i].n, examples[i].x);
if (got != examples[i].want) {
error = 1;
printf("largest_different(%d, %d) = %d, want %d\n",
examples[i].n, examples[i].x, got, examples[i].want);
}
}
return error;
}
There's not always a solution. In that case, the function returns -1.
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;
}