Multiple of 5 checking - c++

How is this code working for multiple of 5
bool isMultipleof5(int n)
{
/* If n is a multiple of 5 then we make sure that last
digit of n is 0 */
if ( (n&1) == 1 )
n <<= 1;
float x = n;
x = ( (int)(x*0.1) )*10;
/* If last digit of n is 0 then n will be equal to (int)x */
if ( (int)x == n )
return true;
return false;
}

It first makes n divisable by 2.
Next, it checks if it is divisable by 10 by multiplying with 0.1 and again with 10. The idea that if it is divisable by 10, you will get back to the original, and only then.
So, if the modifies n is divisable by 10 - it is certainly divisable by 5 as well, and since modified n is always divisable by 2, if it is divisable by 5 it will be divisable by 10, and the algorithm works.
NOTE: This is very unsuggested and especially might break with large values due to floating point precision issues. using the % operator should be prefered: return (n % 5) == 0

This is how the code works with some examples.
if ( (n&1) == 1 ) //Checks if the number is odd
n <<= 1; //Multiplies the number by 2 if odd
x = ( (int)(x * 0.1) //Divides the number 10 then truncates any decimal places
* 10 ) //Multiplies it back by 10
if ( (int)x == n ) //If the floating point value equals the (semi) original value its divisible by 5
return true;
return false; //Other wise false
Example:
15 & 1 == 1 //15 is odd
15 <<= 1; //n is now 30
30 / 10 = 3;
3 * 10 = 30; //x is now 30
30 == 30 //15 is a multiple of 5
17 & 1 == 1 //17 is odd
17 <<= 1; //n is now 34
34 / 10 = 3.4;
((int)3.4 = 3) * 10 = 30; //x is now 30
30 != 34 //17 is not a multiple of 5.
As others said though just simply use the mod operator %.

This is how it works:
Double the number. Now anything ending in 5 will be divisible 10 (and also divisible by 5). n <<= 1; (the check for oddness is unnecessary (n&1) == 1)
Divide it by 10, and cast away the fractional part. (int)(x*0.1)
Multiply it by 10, so now we have the same number as in step 1 only if the number in step 1 was already divisible by 10.
The use of floating point to divide by 10 makes this algorithm dangerous and probably incorrect for large values.

Try this
bool isMultipleof5(int n)
{
return (n%5) == 0;
}

A simpler way would be
bool isMultipleof5(int n)
{
return 0 == ( n % 5 ) ;
}

#define IS_MULTIPLE_OF_5(n) (((n)%5) ? 0 : 1)

I'd agree that (n % 5) == 0 would be an ideal solution, but that wasn't really the question.
This code works because it first checks if the input is odd. If it is, it multiplies by two. Since all odd multiples of 5 end with a 5, multiplying by 2 gives a number that ends with 0.
Then it checks if the last digit is 0. This can only happen if it started as a 0 (i.e. was even, we didn't change it) or if it was odd and ended in a 5 (we multiplied by 2). So, if it ends in 0 then the input must have been divisible by 5.
I'd add that this is also an awkward way to check the value of the last digit. I'd suggest n % 10 == 0 instead, but like others mentioned... you could have just used n % 5 == 0 in the first place ;).

Related

919B | nth Numbers having digit sum as 10 | Codeforces

Here is the link to the question. Essentially, it asks to find the kth number having digit sum as 10. I have tried multiple solutions and also looked upon solutions online. Specifically this one (also shared below). The one with constant time talks about outliers in Arithmetic Progression and uses it to find the nth number having sum as 10. Obviously, the code is incorrect as it fails for test cases when k=1000 etc.
#include <bits/stdc++.h>
using namespace std;
int findNth(int n)
{
int nthElement = 19 + (n - 1) * 9;
int outliersCount = (int)log10(nthElement) - 1;
// find the nth perfect number
nthElement += 9 * outliersCount;
return nthElement;
}
int main()
{
cout << findNth(5) << endl;
return 0;
}
Eventually, I ended up writing combination of Arithmetic Progression + brute force as below
#include <bits/stdc++.h>
using namespace std;
#define ll unsigned long long
int main() {
int n;
cin >> n;
int count = 0;
ll i = 19;
for (; ; i += 9) {
int curr = i;
int localSum = 0;
while (curr) {
localSum += curr%10;
curr /= 10;
}
if (localSum == 10) {
count += 1;
}
if (count == n) {
break;
}
}
cout << i << endl;
return 0;
}
I am wondering, if there is no constant time or better algorithm that does not require me to calculate the sum, but my algorithm always hops in a way that I have number whose digit sum is 10?
Here is a Python solution that you can translate into C++.
cached_count_ds_l = {}
def count_digit_sum_length (s, l):
k = (s, l)
if k not in cached_count_ds_l:
if l < 2:
if s == 0:
return 1
elif l == 1 and s < 10:
return 1
else:
return 0
else:
ans = 0
for i in range(min(10, s+1)):
ans += count_digit_sum_length(s-i, l-1)
cached_count_ds_l[k] = ans
return cached_count_ds_l[k]
def nth_of_sum (s, n):
l = 0
while count_digit_sum_length(s, l) < n:
l += 1
digits = []
while 0 < l:
for i in range(10):
if count_digit_sum_length(s-i, l-1) < n:
n -= count_digit_sum_length(s-i, l-1)
else:
digits.append(str(i))
s -= i
l -= 1
break
return int("".join(digits))
print(nth_of_sum(10, 1000))
The idea is to use dynamic programming to find how many numbers there are of a given maximum length with a given digit sum. And then to use that to cross off whole blocks of numbers on the way to finding the right one.
The main logic goes like this:
0 numbers of length 0 sum to 10
- need longer
0 numbers of length 1 sum to 10
- need longer
9 numbers of length 2 sum to 10
- need longer
63 numbers of length 3 sum to 10
- need longer
282 numbers of length 4 sum to 10
- need longer
996 numbers of length 5 sum to 10
- need longer
2997 numbers of length 6 sum to 10
- answer has length 6
Looking for 1000th number of length 6 that sums to 10
- 996 with a leading 0 sum to 10
- Need the 4th past 99999
- 715 with a leading 1 sum to 10
- Have a leading 1
Looking for 4th number of length 5 that sums to 9
- 495 with a leading 0 sum to 9
- Have a leading 10
Looking for 4th number of length 4 that sums to 9
- 220 with a leading 0 sum to 9
- Have a leading 100
Looking for 4th number of length 3 that sums to 9
- 55 with a leading 0 sum to 9
- Have a leading 1000
Looking for 4th number of length 2 that sums to 9
- 1 with a leading 0 sum to 9
- Need the 3rd past 9
- 1 with a leading 1 sum to 9
- Need the 2nd past 19
- 1 with a leading 2 sum to 9
- Need the 1st past 29
- 1 with a leading 3 sum to 9
- Have a leading 10003
Looking for 1st number of length 1 that sums to 6
- 0 with a leading 0 sum to 6
- Need the 1st past 0
- 0 with a leading 1 sum to 6
- Need the 1st past 1
- 0 with a leading 2 sum to 6
- Need the 1st past 2
- 0 with a leading 3 sum to 6
- Need the 1st past 3
- 0 with a leading 4 sum to 6
- Need the 1st past 4
- 0 with a leading 5 sum to 6
- Need the 1st past 5
- 1 with a leading 6 sum to 6
- Have a leading 100036
And it finishes in a fraction of a second.
Incidentally the million'th is 20111220000010, the billionth is 10111000000002000000010000002100, and the trillionth is 10000000100000100000100000000000001000000000000100000000010110001000.

C++ last digit of a random sequence of powers

I realise that there are several topics already covering this. But my question is not regarding how to build such an algorithm, rather in finding what mistake I have made in my implementation that's causing a single test out of dozens to fail.
The challenge: supplied with a std::list<int> of random numbers, determine the last digit of x1 ^ (x2 ^ (x3 ^ (... ^ xn))). These numbers are large enough, or the lists long enough, that the result is astronomical and cannot be handled by traditional means.
My solution: I chose to use a modular arithmetic approach. In short, the last digit of these huge powers will be the same as that of a reduced power consisting of the first digit of the base (mod 10), raised to the last two digits of the exponent (mod 100). The units in a sequence of powers repeat in patterns of 4 at most, so we can use mod 4 to reduce the exponent, offset by 4 to avoid remainders of 0. At least, this is my understanding of it so far based on the following resources: brilliant / quora.
#include <list>
#include <cmath>
int last_digit(std::list<int> arr)
{
// Break conditions, extract last digit
if (arr.size() == 1) return arr.back() % 10;
if (arr.size() == 0) return 1;
// Extract the last 2 items in the list
std::list<int> power(std::prev(arr.end(), 2), arr.end());
arr.pop_back(); arr.pop_back();
// Treat them as the base and exponent for this recursion
long base = power.front(), exponent = power.back(), next;
// Calculate the current power
switch (exponent)
{
case 0: next = 1; break;
case 1: next = base % 100; break;
default: next = (long)std::pow(base % 10, exponent % 4 + 4) % 100;
}
if (base != 0 && next == 0) next = 100;
// Add it as the last item in the list
arr.push_back(next);
// Recursively deal with the next 2 items in the list
return last_digit(arr);
}
Random example: 123,232 694,027 140,249 ≡ 8
First recrusion: { 123'232, 694'027, 140'249 }
base: 694,027 mod 10 = 7
exponent: 140,249 mod 4 + 4 = 5
next: 75 = 16,807 mod 100 = 7
Second recursion: { 123'232, 7 }
base: 123,232 mod 10 = 2
exponent: 7 mod 4 + 4 = 7
next: 27 = 128 mod 100 = 28
Third recursion: { 28 }
return: 28 mod 10 = 8
The problem: this works for dozens of test cases (like the one above), but fails for 2 2 101 2 ≡ 6.
By hand:
1012 = 10,201
210,201 mod 4 = 0, + 4 = 4
24 = 16 // 6 -correct
Following the algorithm, however:
First recursion: { 2, 2, 101, 2 }
base: 101 mod 10 = 1
exponent: 2 mod 4 + 4 = 6
next: 16 = 1 mod 100 = 1
Second recursion: { 2, 2, 1 } (we can already see that the result is going to be 4)
exponent = 1, next = 2 mod 100 = 2
Third recursion: { 2, 2 }
base: 2 mod 10 = 2
exponent: 2 mod 4 + 4 = 6
next: 26 = 64 mod 100 = 64
Fourth recursion: { 64 }
return 64 mod 10 = 4 // -wrong
In a way, I see what's going on, but I'm not entirely sure why it's happening for this one specific case, and not for dozens of others. I admit I'm rather pushing the limits of my maths knowledge here, but I get the impression I'm just missing a tiny part of the puzzle.
I reckon this post is long and arduous enough as it is. If anyone has any insights into where I'm going wrong, I'd appreciate some pointers.
There's a lot of problems regarding the modulo of a really big number and a lot of the sol'ns back there was basically based on basic number theory. Fermat's Little Theorem, Chinese Remainder Theorem, and the Euler's Phi Function can all help you solve such problems. I recommend you to read "A Computational Introduction to Number Theory and Algebra" by Victor Shoup. It'll help you a lot to better simplify and approach number theory-related questions better. Here's the link for the book in case you'll browse this answer.

Write a program that outputs the total of 5-digit numbers with a five in them, but not with an 8

My challenge is to output the total number of five-digit numbers that have a digit 5, but no digits 8. My only two answers so far have been 0, or 90000. Can anyone help me?
#include <iostream>
using namespace std;
int main() {
int number;
int counter=10000;
int ncounter=0;
while (counter >= 10000 && counter <= 99999) {
int n1,n2,n3,n4,n5;
counter = counter + 1;
n1 = number%10;
number /= 10;
n2 = number%10;
number /= 10;
n3 = number%10;
number /= 10;
n4 = number%10;
number /=10;
n5 = number%10;
number /= 10;
if (n1 == 5||n2 == 5||n3 == 5||n4 == 5||n5 == 5)
if (n1!=8)
if (n2!=8)
if (n3!=8)
if(n4!=8)
if (n5!=8)
ncounter=ncounter+1;
}
cout<<ncounter<<endl;
return 0;
}
(num with 5 but not 8) = (num without 8) - (num with neither 8 nor 5) = 8*9*9*9*9 - 7*8*8*8*8= 23816
Each number is a selection of 5 digits (with repetitions).
Since you cannot select the digit 8, you have 9 possible digits, so this problem is equivalent to the same problem, base 9 (instead of base 10).
If you make 1 digit a 5, there are 4 non-5 and non-8 digits remaining. The number of these can be calculated as 8^4 (because there are 8 available digits to choose from, and you need to choose 4 of these). With a single 5, there are 5 ways to position the 5, so multiply by 5.
Similarly with 2 5's, there are 10 ways to position the 5s relative to other digits.
Therefore, we have the following table:
number of digits==5 remaining digits ways to position 5s
1 8^4 5
2 8^3 10 = 5*4/2
3 8^2 10
4 8^1 5
5 8^0 1
There are 5*8^4 + 10*8^3 + 10*8^2 + 5*8^1 + 8^0 = 26281 numbers <10^5 with a 5 but not an 8.
There are 4*8^3 + 6*8^2 + 4*8^1 + 8^0 = 2465 numbers <10^4 with a 5 but not an 8. Therefore, there are 23816 numbers satisfying your criteria.
This is actually a mathematical problem. Here we have three conditions:
First digit is not zero, as it should be a five-digit number.
No digits are 8
One or more digits are 5
There can be numbers with one to five 5s, where first digit is or is not 5 (except for 55555). That's nine cases to count.
If first digit is not 5, it has 7 options: [1234679]; if any other digit is not 5, it has 8 options: [12346790].
Here C(5) is number of combinations to place 5s, and C(o) - to place other digits.
N(5). 1st? C(5) C(o)
1 Y 1 * 8^4
1 N 4 * 7*8^3
2 Y 4 * 8^3
2 N 6 * 7*8^2
3 Y 6 * 8^2
3 N 4 * 7*8
4 Y 4 * 8
4 N 1 * 7
5 Y 1
Sum: 23816

need algorithm to find the nth palindromic number

consider that
0 -- is the first
1 -- is the second
2 -- is the third
.....
9 -- is the 10th
11 -- is the 11th
what is an efficient algorithm to find the nth palindromic number?
I'm assuming that 0110 is not a palindrome, as it is 110.
I could spend a lot of words on describing, but this table should be enough:
#Digits #Pal. Notes
0 1 "0" only
1 9 x with x = 1..9
2 9 xx with x = 1..9
3 90 xyx with xy = 10..99 (in other words: x = 1..9, y = 0..9)
4 90 xyyx with xy = 10..99
5 900 xyzyx with xyz = 100..999
6 900 and so on...
The (nonzero) palindromes with even number of digits start at p(11) = 11, p(110) = 1001, p(1100) = 100'001,.... They are constructed by taking the index n - 10^L, where L=floor(log10(n)), and append the reversal of this number: p(1101) = 101|101, p(1102) = 102|201, ..., p(1999) = 999|999, etc. This case must be considered for indices n >= 1.1*10^L but n < 2*10^L.
When n >= 2*10^L, we get the palindromes with odd number of digits, which start with p(2) = 1, p(20) = 101, p(200) = 10001 etc., and can be constructed the same way, using again n - 10^L with L=floor(log10(n)), and appending the reversal of that number, now without its last digit: p(21) = 11|1, p(22) = 12|1, ..., p(99) = 89|8, ....
When n < 1.1*10^L, subtract 1 from L to be in the correct setting with n >= 2*10^L for the case of an odd number of digits.
This yields the simple algorithm:
p(n) = { L = logint(n,10);
P = 10^(L - [1 < n < 1.1*10^L]); /* avoid exponent -1 for n=1 */
n -= P;
RETURN( n * 10^L + reverse( n \ 10^[n >= P] ))
}
where [...] is 1 if ... is true, 0 else, and \ is integer division.
(The expression n \ 10^[...] is equivalent to: if ... then n\10 else n.)
(I added the condition n > 1 in the exponent to avoid P = 10^(-1) for n=0. If you use integer types, you don't need this. Another choice it to put max(...,0) as exponent in P, or use if n=1 then return(0) right at the start. Also notice that you don't need L after assigning P, so you could use the same variable for both.)

Calculating Hamming Sequence in C++ (a sequence of numbers that has only 2, 3, and 5 as dividers) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating a sequence using prime numbers 2, 3, and 5 only, and then displaying an nth term (C++)
I've been brainstorming over this forever, and I just can't figure this out. I need to solve the following problem:
Generate the following sequence and display the nth term in the
sequence
2,3,4,5,6,8,9,10,12,15, etc..... Sequence only has Prime numbers
2,3,5
I need to use basic C++, such as while, for, if, etc. Nothing fancy. I can't use arrays simply because I don't know much about them yet, and I want to understand the code for the solution.
I'm not asking for a complete solution, but I am asking for guidance to get through this... please.
My problem is that I can't figure out how to check if the number if the number in the sequence is divisible by any other prime numbers other than 2, 3, and 5.
Also let's say I'm checking the number like this:
for(int i=2; i<n; i++){
if(i%2==0){
cout<<i<<", ";
}else if(i%3==0){
cout<<i<<", ";
}else if(i%5==0){
cout<<i<<", ";
}
It doesn't work simply due to the fact that it'll produce numbers such as 14, which can be divided by prime number 7. So I need to figure out how to ensure that that sequence is only divisible by 2, 3, and 5..... I've found lots of material online with solutions for the problem, but the solutions they have are far too advance, and I can't use them (also most of them are in other languages... not C++). I'm sure there's a simpler way.
The problem with your code is that you just check one of the prime factors, not all of them.
Take your example of 14. Your code only checks if 2,3 or 5 is a factor of 14, which is not exactly what you need. Indeed, you find that 2 is a factor of 14, but the other factor is 7, as you said. What you are missing is to further check if 7 has as only factors 2,3 and 5 (which is not the case). What you need to do is to eliminate all the factors 2,3 and 5 and see what is remaining.
Let's take two examples: 60 and 42
For 60
Start with factors 2
60 % 2 = 0, so now check 60 / 2 = 30.
30 % 2 = 0, so now check 30 / 2 = 15.
15 % 2 = 1, so no more factors of 2.
Go on with factors 3
15 % 3 = 0, so now check 15 / 3 = 5.
5 % 3 = 2, so no more factors of 3.
Finish with factors 5
5 % 5 = 0, so now check 5 / 5 = 1
1 % 5 = 1, so no more factors of 5.
We end up with 1, so this number is part of the sequence.
For 42
Again, start with factors 2
42 % 2 = 0, so now check 42 / 2 = 21.
21 % 2 = 1, so no more factors of 2.
Go on with factors 3
21 % 3 = 0, so now check 21 / 3 = 7.
7 % 3 = 1, so no more factors of 3.
Finish with factors 5
7 % 5 = 2, so no more factors of 5.
We end up with 7 (something different from 1), so this number is NOT part of the sequence.
So in your implementation, you should probably nest 3 while loops in your for loop to reflect this reasoning.
Store the next i value in temporary variable and then divide it by 2 as long as you can (eg. as long as i%2 == 0). Then divide by 3 as long as you can. Then by 5. And then check, what is left.
What about this?
bool try_hamming(int n)
{
while(n%2 == 0)
{
n = n/2;
}
while(n%3 == 0)
{
n = n/3;
}
while(n%5 == 0)
{
n = n/5;
}
return n==1;
}
This should return true when n is a hamming nummer and false other wise. So the main function could look something like this
#include<iostream>
using namespace std;
main()
{
for(int i=2;i<100;++i)
{
if(try_hamming(i) )
cout<< i <<",";
}
cout<<end;
}
this schould print out all Hamming numbers less then 100