Get number of digits in an int without divided by 10 [closed] - c++

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 4 years ago.
Improve this question
Is there a way to get the number of digits without the division by 10?
For example i have this:
int main()
{
int dividend = 100;
int remainder=0;
int temp = 0;
while(dividend>=10)
{
dividend = dividend-10;
temp+=1;
}
printf("Quotient: %d\n",temp);
printf("Reminder: %d\n",dividend);
}
And now I will add to calculate the number of digits of the variable dividend.

You have to know the maximum range of integer to make this function usefull.
no function call, no division ...
int nbDigitInteger(int number)
{
if (-10 < number && number < 10) return (1);
if (-100 < number && number < 100) return (2);
if (-1000 < number && number < 1000) return (3);
if (-10000 < number && number < 10000) return (4);
if (-100000 < number && number < 100000) return (5);
...
}
Sometime, the simplier is the best.

If you are allowed to use logarithms then
int i = 123456;
int digitsCount = ceil(log10(abs(i)+1.0));
cout << digitsCount;
6

Your question is too broad, and the code is also unrelated.
Since you attempted to post the code, I'll provide the guidelines for the problem you asked for. Write the code yourself.
Take the absolute integer value. (abs())
Print it to a (large enough) buffer. (sprintf()/ snprintf()).
Use strlen() to get the length of the buffer (as string).

An alternative to the very elegant solution o #Yola is this.
intPow10 is returning 10 to the power exponent. I did not use pow from math.h, since it is numerically expensive and as #Tom's pointed out it can lead to invalid results.
#include <stdio.h>
#include<math.h>
int intPow10(int exponent){
int retval=1;
while (exponent){
retval *=10;
exponent --;
}
return retval;
}
int numDigits(const int i) {
int digits = 1;
while (intPow10(digits) <= fabs(i)) {
digits++;
}
printf("%i has %i digits.\n", i,digits);
return digits;
}
int main() {
numDigits(1);
numDigits(-1);
numDigits(10);
numDigits(13);
numDigits(-112312);
}

Is this code golf or what?
int b = 1000;
char a[10] = itoa(b);
printf("%d\n", strlen(a)); // 4
This simply turns b into a string, which is a. Then, prints the length. What would we do without atoi() and itoa()? Our own functions!

Related

C++: Could someone help me optimize my solution? [closed]

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 1 year ago.
Improve this question
Program adds 2 fractions and displays their sum in a reduced form (n times). Could someone help me optimize my solution (According to SPOJ, the time limit has been exceeded)
My solution:
#include <iostream>
using namespace std;
int main()
{
int n, a, b, c, d, gcd;
long long num, den;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a >> b >> c >> d;
num = (a*d)+(b*c);
den = b*d;
for(int j = 1; j <= num && j <= den; ++j)
{
if(num % j == 0 && den % j == 0)
{
gcd = j;
}
}
cout << num/gcd << " " << den/gcd << endl;
}
}
The key step in your code is computing the greatest common divisor of num and den. The code does this by testing every number less than or equal to either of them to find the largest that divides both. While this is a correct algorithm, it is very slow, requiring time proportional to whichever is smaller.
To make this faster, use the Euclidean algorithm, which takes time proportional to the logarithm of the smaller number, which means it is much faster. The essence of this algorithm is to divide one number by the other and replace the larger with the resulting remainder until that remainder is zero. Concretely, copying and slightly reformatting the code from tutorialspoint.com:
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
Alternatively, as noted in a comment by #badfilms, C++17 contains std::gcd in the library.

Codeforces Problem 110A - Trouble with a certain input [closed]

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 1 year ago.
Improve this question
Problem:
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.
Input
The only line contains an integer n (1 ≤ n ≤ 1018).
Output
Print on the single line "YES" if n is a nearly lucky number. Otherwise, print "NO" (without the quotes).
I submitted a solution on this problem and fail at the input of 4744000695826. This should give an output of YES, since it has 4 lucky numbers, and 4 is a lucky number itself. However I get an output of NO. This was the first input test which contained 4s and 7s and was bigger than 32 bit int limit 232-1, so I guess that has something to do with it, but I honestly don't know.
Here is my code:
#include <iostream>
#include <cmath>
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
// counting digits in an int
int count_digit(int number) {
return int(log10(number) + 1);
}
// counting certain digits in an int
int counter(int b, int n) {
int count = 0;
while(b > 0) {
if(b % 10 == n) {
count++;
}
b /= 10;
}
return count;
}
int main()
{
int k;
cin >> k;
int r = counter(k,4) + counter(k,7);
if (count_digit(r) - (counter(r,4) + counter(r,7)) == 0) {
cout << "YES";
}
else {
cout << "NO";
}
return 0;
}
If you want to process numbers greater than your ints, you need to use something else.
For example, you could:
std::string number;
std::cin >> number;
Then you can check the number with
char value = '5';
for(const char& c: number)
{
if (c == value);
}
That way you're not even limited to 64 bits.
Even more modern/idiomatic would be to use std::count:
https://en.cppreference.com/w/cpp/algorithm/count

minimum number of moves required to convert a given into a lucky number [closed]

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 1 year ago.
Improve this question
You are given a number, at a time either you can increase a number by 1 or decrease by 1 it is considered as one move find the minimum number of moves required to convert a given into a lucky number. A number is called lucky if all the digits in it are even.
I have writtern the code but I am not sure if it is correct. Can anybody please confirm me?
#include<bits/stdc++.h>
using namespace std;
int count(int n)
{
int count = 0;
while (n != 0)
{
n = n / 10;
++count;
}
return count;
}
int firstDigit(int n)
{
// Remove last digit from number
// till only one digit is left
while (n >= 10)
n /= 10;
// return the first digit
return n;
}
int main()
{
int n;
cin >> n;
int i,j,ans=0;
int x = count(n);
while(x--)
{
if(firstDigit(n)%2 != 0)
{
if(firstDigit(n) == 9)
{
ans = ans + pow(10,x);
n = n-pow(10,x);
}
else
{
ans = ans + pow(10,x);
n = n + pow(10,x);
}
}
else
n = n - pow(10,x);
}
cout << ans << endl;
}
Edit:
I found it is giving wrong answer at 100. Can you please help me in finding out the mistake
Not all code can easily be tested, thats why you should strive to write testable code right from the start (instead of first writing it all and then try to confirm correctness). In your case testability could benefit a lot from moving most logic from main into a dedicated function:
int minimal_steps(int input) {
....
}
Once you have that, you can either call it in main with user supplied input just as you do it now, but you can also write tests more easily:
void test() {
assert( minimal_steps(2222) == 0);
assert( minimal_steps(2221) == 1);
...etc...
}
Once you got into the habit of testing your code (you should also write tests for count and firstDigit) you may consider to use a testing framework to automate tests.
PS: It isnt wrong, but it is such a waste of CPU cycles that it is worth mentioning (actually it was already mentioned in a comment). You do not need to compute pow(10,x) in a loop where x is the loop counter. Consider that you are computing 10^2 almost as many times as the loop has iterations. Also 10^3 is the same in every iteration. Instead you should only update with *10 (in case x is incremented) or /10 when x decrements between iterations. Moreover, pow is for floating-points, not for integers.

c++ how to store a variable and string that is 2^1 000 000 large? [closed]

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
I am trying to solve an exercise. It says that i need to output 3 last digits of a number that is 2 raised to the power of n (2^n).
But input is n=1000000.
The code works with lower values, but when the input is 1 000 000 the number gets too large.
My code:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
unsigned long long n;
cin >> n;
unsigned long long sk = pow(2, n);
if (sk < 1000) cout << sk;
else {
string ats = to_string(sk); // converting the number to string
// so I could output 3 last digits
// probably not the best solution
// for this exercise
n = ats.length();
for (unsigned long long i = n - 3; i < n; i++) {
cout << ats[i];
}
}
return 0;
}
Thank you for your help.
Try something like:
Initialize result to 1
Within a loop from 1 to n:
result *= 2
result %= 1000
This because the result of the last 3 digits does not depend upon the greater digits
You can calculate your number modulo 1000. Just saving the three least significant digits and trashing the more significant ones does not alter the result.
Just do:
int result = 1;
for(int i = 0; i < n; i++){
result = (result * 2) % 1000;
}

How to calculate how many times a number goes into another number [closed]

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 6 years ago.
Improve this question
This is the program with the initial 'number' stated in the question taken as 'n' and the 'other number' taken as 10.
void divideme()
static int count=0; //initalised a variable which I'll be returning the value of.
int n;
cin>>n;//taken input of variable which I want to divide by another number (say 10 in this case)
int &rem=n;//created a reference variable which stores the value of n.
while (rem>=10) {
rem=rem%10; //this is to be corrected as rem = rem - 10;
count++;
}
return count;
Your code is overkill. Just do the division one time. The result is the number of times 10 goes into the number. No loop is needed at all. The % operator gives you the modulus (remainder) of a division, which is not what you need in this situation.
int divideme()
{
int n;
cin>>n; //get input which I want to divide by another number (say 10 in this case)
return (n / 10);//return how many times it divides by 10
}
For example:
9 / 10 = 0
9 % 10 = 9
10 goes into 9 0 times, with a remainder of 9.
12345 / 10 = 1234
12345 % 10 = 5
10 goes into 12345 1234 times, with a remainder of 5.
The % operator give you the modulus, which is the remainder after division.
If you just want to count the number of times that 10 goes into a number rem, then replace
rem=rem%10;
with
rem = rem - 10;
in your loop.
(Also, you don't need if (rem>=10) in your code. The while loop takes care of this.)
#include <cmath>
#include <iostream>
int times_divided_by_10(int x)
{
return int(std::log10(double(x)));
}
int main()
{
std::cout << times_divided_by_10(101) << std::endl;
}
expected output:
2
another way:
#include <iostream>
int times_divided_by_10(int x)
{
int count = 0;
while (x >= 10) {
++count;
x /= 10;
}
return count;
}
int main()
{
std::cout << times_divided_by_10(101) << std::endl;
}