I came across an interesting problem:
How would you count the number of 1 digits in the representation of 11 to the power of N, 0<N<=1000.
Let d be the number of 1 digits
N=2 11^2 = 121 d=2
N=3 11^3 = 1331 d=2
Worst time complexity expected O(N^2)
The simple approach where you compute the number and count the number of 1 digits my getting the last digit and dividing by 10, does not work very well. 11^1000 is not even representable in any standard data type.
Powers of eleven can be stored as a string and calculated quite quickly that way, without a generalised arbitrary precision math package. All you need is multiply by ten and add.
For example, 111 is 11. To get the next power of 11 (112), you multiply by (10 + 1), which is effectively the number with a zero tacked the end, added to the number: 110 + 11 = 121.
Similarly, 113 can then be calculated as: 1210 + 121 = 1331.
And so on:
11^2 11^3 11^4 11^5 11^6
110 1210 13310 146410 1610510
+11 +121 +1331 +14641 +161051
--- ---- ----- ------ -------
121 1331 14641 161051 1771561
So that's how I'd approach, at least initially.
By way of example, here's a Python function to raise 11 to the n'th power, using the method described (I am aware that Python has support for arbitrary precision, keep in mind I'm just using it as a demonstration on how to do this an an algorithm, which is how the question was tagged):
def elevenToPowerOf(n):
# Anything to the zero is 1.
if n == 0: return "1"
# Otherwise, n <- n * 10 + n, once for each level of power.
num = "11"
while n > 1:
n = n - 1
# Make multiply by eleven easy.
ten = num + "0"
num = "0" + num
# Standard primary school algorithm for adding.
newnum = ""
carry = 0
for dgt in range(len(ten)-1,-1,-1):
res = int(ten[dgt]) + int(num[dgt]) + carry
carry = res // 10
res = res % 10
newnum = str(res) + newnum
if carry == 1:
newnum = "1" + newnum
# Prepare for next multiplication.
num = newnum
# There you go, 11^n as a string.
return num
And, for testing, a little program which works out those values for each power that you provide on the command line:
import sys
for idx in range(1,len(sys.argv)):
try:
power = int(sys.argv[idx])
except (e):
print("Invalid number [%s]" % (sys.argv[idx]))
sys.exit(1)
if power < 0:
print("Negative powers not allowed [%d]" % (power))
sys.exit(1)
number = elevenToPowerOf(power)
count = 0
for ch in number:
if ch == '1':
count += 1
print("11^%d is %s, has %d ones" % (power,number,count))
When you run that with:
time python3 prog.py 0 1 2 3 4 5 6 7 8 9 10 11 12 1000
you can see that it's both accurate (checked with bc) and fast (finished in about half a second):
11^0 is 1, has 1 ones
11^1 is 11, has 2 ones
11^2 is 121, has 2 ones
11^3 is 1331, has 2 ones
11^4 is 14641, has 2 ones
11^5 is 161051, has 3 ones
11^6 is 1771561, has 3 ones
11^7 is 19487171, has 3 ones
11^8 is 214358881, has 2 ones
11^9 is 2357947691, has 1 ones
11^10 is 25937424601, has 1 ones
11^11 is 285311670611, has 4 ones
11^12 is 3138428376721, has 2 ones
11^1000 is 2469932918005826334124088385085221477709733385238396234869182951830739390375433175367866116456946191973803561189036523363533798726571008961243792655536655282201820357872673322901148243453211756020067624545609411212063417307681204817377763465511222635167942816318177424600927358163388910854695041070577642045540560963004207926938348086979035423732739933235077042750354729095729602516751896320598857608367865475244863114521391548985943858154775884418927768284663678512441565517194156946312753546771163991252528017732162399536497445066348868438762510366191040118080751580689254476068034620047646422315123643119627205531371694188794408120267120500325775293645416335230014278578281272863450085145349124727476223298887655183167465713337723258182649072572861625150703747030550736347589416285606367521524529665763903537989935510874657420361426804068643262800901916285076966174176854351055183740078763891951775452021781225066361670593917001215032839838911476044840388663443684517735022039957481918726697789827894303408292584258328090724141496484460001, has 105 ones
real 0m0.609s
user 0m0.592s
sys 0m0.012s
That may not necessarily be O(n2) but it should be fast enough for your domain constraints.
Of course, given those constraints, you can make it O(1) by using a method I call pre-generation. Simply write a program to generate an array you can plug into your program which contains a suitable function. The following Python program does exactly that, for the powers of eleven from 1 to 100 inclusive:
def mulBy11(num):
# Same length to ease addition.
ten = num + '0'
num = '0' + num
# Standard primary school algorithm for adding.
result = ''
carry = 0
for idx in range(len(ten)-1, -1, -1):
digit = int(ten[idx]) + int(num[idx]) + carry
carry = digit // 10
digit = digit % 10
result = str(digit) + result
if carry == 1:
result = '1' + result
return result
num = '1'
print('int oneCountInPowerOf11(int n) {')
print(' static int numOnes[] = {-1', end='')
for power in range(1,101):
num = mulBy11(num)
count = sum(1 for ch in num if ch == '1')
print(',%d' % count, end='')
print('};')
print(' if ((n < 0) || (n > sizeof(numOnes) / sizeof(*numOnes)))')
print(' return -1;')
print(' return numOnes[n];')
print('}')
The code output by this script is:
int oneCountInPowerOf11(int n) {
static int numOnes[] = {-1,2,2,2,2,3,3,3,2,1,1,4,2,3,1,4,2,1,4,4,1,5,5,1,5,3,6,6,3,6,3,7,5,7,4,4,2,3,4,4,3,8,4,8,5,5,7,7,7,6,6,9,9,7,12,10,8,6,11,7,6,5,5,7,10,2,8,4,6,8,5,9,13,14,8,10,8,7,11,10,9,8,7,13,8,9,6,8,5,8,7,15,12,9,10,10,12,13,7,11,12};
if ((n < 0) || (n > sizeof(numOnes) / sizeof(*numOnes)))
return -1;
return numOnes[n];
}
which should be blindingly fast when plugged into a C program. On my system, the Python code itself (when you up the range to 1..1000) runs in about 0.6 seconds and the C code, when compiled, finds the number of ones in 111000 in 0.07 seconds.
Here's my concise solution.
def count1s(N):
# When 11^(N-1) = result, 11^(N) = (10+1) * result = 10*result + result
result = 1
for i in range(N):
result += 10*result
# Now count 1's
count = 0
for ch in str(result):
if ch == '1':
count += 1
return count
En c#:
private static void Main(string[] args)
{
var res = Elevento(1000);
var countOf1 = res.Select(x => int.Parse(x.ToString())).Count(s => s == 1);
Console.WriteLine(countOf1);
}
private static string Elevento(int n)
{
if (n == 0) return "1";
//Otherwise, n <- n * 10 + n, once for each level of power.
var num = "11";
while (n > 1)
{
n--;
// Make multiply by eleven easy.
var ten = num + "0";
num = "0" + num;
//Standard primary school algorithm for adding.
var newnum = "";
var carry = 0;
foreach (var dgt in Enumerable.Range(0, ten.Length).Reverse())
{
var res = int.Parse(ten[dgt].ToString()) + int.Parse(num[dgt].ToString()) + carry;
carry = res/10;
res = res%10;
newnum = res + newnum;
}
if (carry == 1)
newnum = "1" + newnum;
// Prepare for next multiplication.
num = newnum;
}
//There you go, 11^n as a string.
return num;
}
First of all: before you downgrade THIS IS NOT MY HOMEWORK, this question belongs to codingbat or eulerproject or another website. I am NOT asking you to give me a fully completed and coded answer I am asking you to give me some ideas to HELP me.
Later on, I am having a time limit trouble with this problem. I actually solved it but my solution is too slow. It needs to be done within at 0 to 1 second. In the worst case scenario my code consumes more than 8 seconds. If you could help me with some ideas or if you could show me a more accurate solution pseudo code etc. I would really appreciate it.
First input means how many times we are going to process. Later on, user enters two numbers [X, Y], (0 < X < Y < 100000) We need to compute the most frequent digit in the range of these two numbers X and Y. (including X and Y) Besides, If multiple digits have the same maximum frequency than we suppose to print the smallest of them.
To illustrate:
User first enters number of test cases: 7
User enters X and Y(first test case): 0 21
Now I did open all digits in my solution you may have another idea you are free to use it but to give you a hint: We need to treat numbers like this: 0 1 2 3 ... (here we should open 10 as 1 and 0 same for all of them) 1 0 1 1 1 2 1 3 ... 1 9 2 0 2 1 than we show the most frequent digit between 0 and 21 (In this case: 1)
More examples: (Test cases if you want to check your solution)
X: 7 Y: 956 Result: 1
X: 967 Y: 8000 Result: 7
X: 420 Y: 1000 Result: 5 etc.
Here's my code so far:
package most_frequent_digit;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Main
{
public static int secondP = 0;
public static void getPopularElement(int[] list)
{
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer nextInt : list)
{
Integer count = map.get(nextInt);
if (count == null)
{
count = 1;
} else
{
count = count + 1;
}
map.put(nextInt, count);
}
Integer mostRepeatedNumber = null;
Integer mostRepeatedCount = null;
Set<Integer> keys = map.keySet();
for (Integer key : keys)
{
Integer count = map.get(key);
if (mostRepeatedNumber == null)
{
mostRepeatedNumber = key;
mostRepeatedCount = count;
} else if (count > mostRepeatedCount)
{
mostRepeatedNumber = key;
mostRepeatedCount = count;
} else if (count == mostRepeatedCount && key < mostRepeatedNumber)
{
mostRepeatedNumber = key;
mostRepeatedCount = count;
}
}
System.out.println(mostRepeatedNumber);
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner read = new Scanner(System.in);
int len = read.nextInt();
for (int w = 0; w < len; w++)
{
int x = read.nextInt();
int y = read.nextInt();
String list = "";
for (int i = x; i <= y; i++)
{
list += i;
}
String newList = "";
newList += list.replaceAll("", " ").trim();
int[] listArr = new int[list.length()];
for (int j = 0; j < newList.length(); j += 2)
{
listArr[secondP] = Character.getNumericValue(newList.charAt(j));
secondP++;
}
getPopularElement(listArr);
secondP = 0;
}
}
}
As you can see it takes too long if user enters X: 0 Y: 1000000 like 8 - 9 seconds. But it supposed to return answer in 1 second. Thanks for checking...
Listing all digits and then count them is a very slow way to do this.
There are some simple cases:
X = 10n, X = 10n+1-1 (n > 0) :
The digits 1 to 9 are appearing 10n + n⋅(10n-10n-1) times, 0 appears n⋅(10n-10n-1) times.
E.g.
10, 99: the digits 1 to 9 are appearing 19 times, 0 appears 9 times.
100, 999: the digits 1 to 9 are appearing 280 times, 0 appears 180 times.
X = a⋅10ⁿ, Y = (a+1)⋅10ⁿ-1 (1 ≤ a ≤ 9):
All digits except for a appears n⋅10n-1, the digit a appears 10n + n⋅10n-1 times.
E.g.
10, 19: all digits except for 1 appear one time, 1 appears 11 times.
20, 299: all digits except for 2 appear 20 times, 2 appears 120 times.
With this cases you can split off the input into sub cases. E.g.
X = 0, Y = 21. Split it up into
X₁ = 0, Y₁ = 9 (special case, but very simple),
X₂ = 10, Y₂ = 19 (case 2),
X₃ = 20, Y₃ = 21 (case 3)
X = 0, Y = 3521. Split it up into
X₁ = 0, Y₁ = 9 (special case, but very simple),
X₂ = 10, Y₂ = 99 (case 1),
X₃ = 100, Y₃ = 999 (case 1),
X₄ = 1000, Y₄ = 1999 (case 2),
X₅ = 2000, Y₅ = 2999 (case 2),
X₆ = 3000, Y₆ = 3521 (case 3)
I left case 3 open. The case looks like X = a⋅10ⁿ, Y = a⋅10ⁿ + b (1 ≤ a ≤ 9, 0 ≤ b < 10ⁿ).
Here you know you get the digit a b-times plus the number of appearances in 0 to b. Since X and Y are n+1 digit numbers, b has n digits, with leading zeros.
The missing parts of case 3 have to be filled by the reader.
I'm looking for algorithm working in loop which will generate any natural number n with using only incrementation and multiplication by 2 well trivial way is known (increment number n times) but I'm looking for something a little bit faster. Honestly I don't even know how I should start this.
Basically, what you want to do is shift in the bits of the number from the right, starting with the MSB.
For example, if your number is 70, then the binary of it is 0b1000110. So, you want to "shift in" the bits 1, 0, 0, 0, 1, 1, 0.
To shift in a zero, you simply double the number. To shift in a one, you double the number, then increment it.
if (bit_to_be_shifted_in != 0)
x = (x * 2) + 1;
else
x = x * 2;
So, if you're given an array of bits from MSB to LSB (i.e. from left to right), then the C code looks like this:
x = 0;
for (i = 0; i < number_of_bits; i++)
{
if (bits[i] != 0)
x = x * 2 + 1;
else
x = x * 2;
}
One way of doing this is to go backwards. If it's an odd number, subtract one. If it's even, divide by 2.
while(n > 0) {
n & 1 ? n &= ~1 : n >>= 1;
}
I am currently building an app in xcode and I have something i'm stuck on... for example if the total of a question came to 15 how do you seperate the "1" and "5" and add those two number and recieve six? and i only want to display the six for my pp user to see
9+6 = 15
nut instead i want it to display as 9+6= 15/6
The wording of your post is a little confusing. Are you asking how to separate numbers into their individual digits, and then do things with those digits?
Not sure exactly what language you're writing in here, but in C:
int firstDigit = 0;
int secondDigit = 0;
int result = 0;
int num = 15;
firstDigit = num % 10; // 15 % 10 = 5
num /= 10; // 15 / 10 = 1
secondDigit = num % 10; // 1 % 10 = 1
result = firstDigit + secondDigit; // 5 + 1 = 6
Taking a number modulo 10 allows you to easily isolate the trailing digit.
You could even throw the above logic (isolate trailing digit, chop off trailing digit) into a loop to deal with arbitrarily-long numbers (within reason, of course).
Is there any algorithm to find out that how many ways are there for write a number for example n , with sum of power of 2 ?
example : for 4 there are four ways :
4 = 4
4 = 2 + 2
4 = 1 + 1 + 1 + 1
4 = 2 + 1 + 1
thanks.
Suppose g(m) is the number of ways to write m as a sum of powers of 2. We use f(m,k) to represent the number of ways to write m as a sum of powers of 2 with all the numbers' power is less than or equal to k. Then we can reduce to the equation:
if m==0 f(m,k)=1;
if k<0 f(m,k)=0;
if k==0 f(m,k)=1;
if m>=power(2,k) f(m,k)=f(m-power(2,k),k)+f(m,k-1);//we can use power(2,k) as one of the numbers or not.
else f(m,k)=f(m,k-1);
Take 6 as an example:
g(6)=f(6,2)
=f(2,2)+f(6,1)
=f(2,1)+f(4,1)+f(6,0)
=f(0,1)+f(2,0)+f(2,1)+f(4,0)+1
=1+1+f(0,1)+f(2,0)+1+1
=1+1+1+1+1+1
=6
Here is the code below:
#include<iostream>
using namespace std;
int log2(int n)
{
int ret = 0;
while (n>>=1)
{
++ret;
}
return ret;
}
int power(int x,int y)
{
int ret=1,i=0;
while(i<y)
{
ret*=x;
i++;
}
return ret;
}
int getcount(int m,int k)
{
if(m==0)return 1;
if(k<0)return 0;
if(k==0)return 1;
if(m>=power(2,k))return getcount(m-power(2,k),k)+getcount(m,k-1);
else return getcount(m,k-1);
}
int main()
{
int m=0;
while(cin>>m)
{
int k=log2(m);
cout<<getcount(m,k)<<endl;
}
return 0;
}
Hope it helps!
A recursive definition of the sequence (from Peter's link to A018819):
f(n) = 1 if n = 0, Sum(j = 0..[n/2], f(j)) if n > 0 http://mathurl.com/nuaarfm.png
You want to find the number of ways in which you can express a number as the sum of the power of 2.
firstly you need to find the number set bits in that particular number because the number of the set bit will give us the minimum numbers required to express it as the sum of the power of 2.
The maximum numbers required to express it as a sum of the power of 2 will the number itself because you can express it as a sum of 1 ( because 2 the power 0 is 1).
example: 5 can be expressed as ( 1+1+1+1+1)
hence the total number of ways to express a number as the power of 2 is simply given by the formula -->
let the no be x
( x - no of set bits in x ) + 1 ;
for example, let the number be 17
then the no of set bits in 17 is 2
hence the no of ways are ( 17 - 2 ) + 1 = 16 ;