solving for an unknown integer using python [closed] - python

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 9 days ago.
Improve this question
I am new to coding in general, so after learning the basics of python from various videos on youtube, I started taking challenges on code wars. there is a particular problem I cant seem to get past. here it is :
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
we want to find a positive integer k, if it exists, such that the sum of the digits of n taken to the successive powers of p is equal to k * n.
In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
Note: n and p will always be given as strictly positive integers.
I tried using if statements but I still was not able to find the k integer, then I tried using a for loop I still had no progress. I will love it if someone gave an assistance on how to get pass this problem.

This is a problem about math and arithmetic, so it helps to think first about math and arithmetic. You can think about programming once your math is right. Math comes first. Here you are asking whether a ** p + b ** (p+1) + ... is a multiple of n. Or in other words, if it is divisible by n. See Wikipedia: Divisor or some other better math resource about arithmetic and divisibility.
a, b, c, d, ... are known. p is known. So the big number of the left of the equal sign is known. Let's call X this number. X = a ** p + b ** (p+1) + ....
n is known too.
You are asking whether X is a multiple of n. There is division and remainder for that. The answer is yes if and only if the remainder x % n is 0, and in that case, k is the quotient k = X // n.
Important note about python: powers in python are noted using **, not ^. This is important because ^ is also an operator in python, but it doesn't mean power at all. So if you write a ^ p you won't get an error with a helpful error message; instead, the code will execute but the result will be garbage. Be careful to write a ** p and not a ^ p.

Related

Why does this code not give the correct result for Project Euler Question #56?

I'm completing the 56th question on Project Euler:
A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, ab, where a, b < 100`, what is the maximum digital sum?
I wrote this code, which gives the wrong answer:
import math
value = 0
a = 1
b = 1
while a < 100:
b = 1
while b < 100:
result = int(math.pow(a,b))
x = [int(a) for a in str(result)]
if sum(x) > value:
value = sum(x)
b = b + 1
a = a + 1
print(value)
input("")
My code outputs 978, whereas the correct answer is
972
I already know the actual approach, but I don't know why my reasoning is incorrect. The value that gives me the greatest digital sum seems to be 8899, but adding together each digit in that result will give me 978. What am I misinterpreting in the question?
math.pow uses floating point numbers internally:
Unlike the built-in ** operator, math.pow() converts both its arguments to type float.
Note that Python integers have no size restriction, so there is no problem computing 88 ** 99 this way:
>>> from math import pow
>>> pow(88, 99)
3.1899548991064687e+192
>>> 88**99
3189954899106468738519431331435374548486457306565071277011188404860475359372836550565046276541670202826515718633320519821593616663471686151960018780508843851702573924250277584030257178740785152
And indeed, this is exactly what the documentation recommends:
Use ** or the built-in pow() function for computing exact integer powers.
The result computed using math.pow will be slightly different, due to the lack of precision of floating-point values:
>>> int(pow(88, 99))
3189954899106468677983468001676918389478607432406058411199358053788184470654582587122118156926366989707830958889227847846886750593566290713618113587727930256898153980172821794148406939795587072
It so happens that the sum of these digits is 978.

Computing directly nth Fibonacci term without finding previous terms using binet's formula. (in O(1) time) [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 2 years ago.
Improve this question
from math import sqrt
n = int(input())
phi = (1 + sqrt(5))/2
fib_n = round((phi**n))
print(fib_n)
The above-mentioned code is not correct, it gives some nearer value to fib_n.
from math import sqrt
n = int(input())
phi = (1 + sqrt(5))/2
fib_n = round((phi**n)/sqrt(5))
print(fib_n)
This code works absolutely perfect after dividing by sqrt(5) in the 6th line.
My doubts are:
What is the significance of dividing by sqrt(5) and why only sqrt(5) and not any other number?
Can I solve the same thing using the floor or ceiling (or any other) and without dividing by root(5)?
Any help/guidance/resources are heavily appreciated!
This is the wrong formula.
The formula should be:
from math import sqrt
n = int(input())
phi1 = (1 + sqrt(5))/2
phi2 = (1 - sqrt(5))/2
fib_n = (pow(phi1, n) - pow(phi2, n)) / sqrt(5)
print(fib_n)
The sqrt(5) comes out of the proof: Proof
Basically, the sqrt(5) comes from solving the partial fractions
Side note: pow(phi, n) is usually more efficient than phi ** n and it can also compute mods. pow(phi, n, m) gives (phi ** n) % m

What is the most efficient way to sum integers in a range? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
for i in range(0,1000000):
j += i
What is the performance issue with this code and how can it be fixed?
My understanding is that it can lead to IntegerOverflow ? If not, what other issues are there and how can it be done in the most efficient way?
Edit: This is an interview question , This has a performance issue and there is a better way to do it according to the question
This is more of a math problem.
If you want to compute the total of positive integers ranging from n to m:
def sum_range(n,m):
d = m - n
return n * (d+1) + int(d*(d+1)/2)
Consider the example sum_range(4,8), you can represent this as summing the x's in this:
xxxx
xxxxx
xxxxxx
xxxxxxx
xxxxxxxx
Which can be broken down into of 4 (n) times 5 (8 - 4 + 1, i.e. the number of numbers) and the sum of the range from 0 to 4:
xxxx
xxxx x
xxxx xx
xxxx xxx
xxxx xxxx
Summing from 0 to n is a well known sum, which comes down to (n * (n+1)) / 2.
Python ints are unbounded - they won't overflow (well, in Python 3 - in Python 2 there were both bounded and unbounded ints).
The problem with summing a range "naively" is merely time. Your loop goes around a million times, but works fine:
>>> j = 0
>>> for i in range(0,1000000):
... j += i
>>> j
499999500000
It's very much faster to think ;-) The sum of an arithmetic sequence is merely its average term times the number of terms. So, for this example:
>>> r = range(0, 1000000)
>>> first = r[0]
>>> last= r[-1]
>>> (first + last) * len(r) // 2
499999500000
Now the number of operations needed is a small constant no matter what the range.
The same code works for any range. For example,
>>> r = range(100000000, 19, -17)
>>> sum(r)
294117697058808
>>> first = r[0]
>>> last = r[-1]
>>> (first + last) * len(r) // 2
294117697058808

Greatest Common Denominator counter [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I wanted to make a greatest common divisor counter in python, but I'm not exactly sure how to go at it, or where to start... Pretty much all I've got is this equation (a and b are numbers):
a = b * quotient + remainder
And I want the counter to print all the steps until remainder is lower than a, and then show the GCD.
I've also searched some more and found out that quotient of 2 numbers can be simply done with the // command and remainder with % command, so basically:
a = b * (a // b) + (a % b)
I'm also aware that I need a loop for the counter, but I've got no idea how to go about that... Help would be most appreciated.
I've seen some codes for GCD, but couldn't find one that would show all the steps.
def gcd_steps(a, b):
steps = []
# this is the standard GCD finding algorithm;
# we simply amend it with "step tracking"
while b:
# a, b = b, a % b
tmp = a
a = b
b = tmp % b
steps.append(a)
return steps # normally we'd want to return `a`
# but you want the steps not just the result
steps = gcd_steps(125 * 123 * 12314, 25 * 149)
# print the list with `->` between the steps
print(" -> ".join(str(x) for x in steps))
(the result would be the last step, which you can access by taking the last element of the list: steps[-1])
Output:
3725 -> 900 -> 125 -> 25

Python factorization program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to programming and I am trying to write a program that takes a positive integer n from input, and then outputs all factorizations of n.
For example if n=10 the program would output
1 times 10 equals 10
2 times 5 equals 10
5 times 2 equals 10
10 times 1 equals 10
I believe the easiest way to do it is to use an if statement nested within for loops. Can anybody provide me with any guidance to help create this? So far I have...
n = int(input())
a = 0
b = n
for a in range(0, n):
if a * b !=n:
continue
if a * b ==n:
print (a+ "times" +b+ "equals" +n)
a=a+1
b=n-1
But for some reason it isn't working. I think I have the right general idea but my code is obviously incorrect.
There are a few issues with your code, but also with your logic. You are increasing a twice (with for and addition), b becomes n-1 the first time through the loop and stays that way, but even if it didn't (eg b = b - 1), it wouldn't work, because if you are increasing a and decreasing b simultaneously, you won't find the correct values unless they happen to match by chance.
Other than that, it's unnecessary to check for a * b != n, you need to call str on the integers to add them to strings and the 0 in your range call is redundant.
whncode's answer is an elegant solution (except for a couple of errors I tried to correct), but to use your logic, you might do this:
for a in range(1, n+1):
for b in range(1, n+1):
if a * b == n:
print str(a) + " times " + str(b) + " equals " + str(n)
n = 10
for divisor in range(n, 0, -1): # reverse range
if (n%divisor == 0): # if modulo is 0
print("%d times %d equals %d", (n/divisor, divisor, n)

Categories