I'm studing recursive function and i faced question of
"Print sum of 1 to n with no 'for' or 'while' "
ex ) n = 10
answer = 55
n = 100
answer = 5050
so i coded
import sys
sys.setrecursionlimit(1000000)
sum = 0
def count(n):
global sum
sum = n
if n!=0:
count(n-1)
count(n = int(input()))
print(sum)
I know it's not good way to get right answer, but there was a solution
n=int(input())
def f(x) :
if x==1 :
return 1
else :
return ((x 1)//2)*((x 1)//2) f(x//2)*2
print(f(n))
and it works super well , but i really don't know how can human think that logic and i have no idea how it works.
Can you guys explain how does it works? Even if i'm looking that formula but i don't know why he(or she) used like that And i wonder there is another solution too (I think it's reall important to me)
I'm really noob of python and code so i need you guys help, thank you for watching this
CodePudding user response:
Here is a recursive solution.
def rsum(n):
if n == 1: # BASE CASE
return 1
else: # RECURSIVE CASE
return n rsum(n-1)
You can also use range and sum to do so.
n = 100
sum_1_to_n = sum(range(n 1))
CodePudding user response:
There is 2 ways to find the answer
1. Recursion
def sum(n):
if n == 1:
return 1
if n <= 0:
return 0
else:
return n sum(n-1)
print(sum(100))
This is a simple recursion code, when you try to apply the reccurent function F_n = n F_(n-1) to find the answer
2. Formula
Let S = 1 2 3 ... n
Then lets do something like this
S = 1 2 3 ... n
S = n (n - 1) (n - 2) ... 1
Let's combine them and we get
2S = (n 1) (n 1) ... (n 1) - n times
From that you get
S = ((n 1) * n) / 2
So for n = 100 you get
S = 101 * 100 / 2 = 5050
So in python you will get something like
sum = lambda n: ( (n 1) * n) / 2
print(sum(100))
CodePudding user response:
you can try this:
def f(n):
if n == 1:
return 1
return n f(n - 1)
print(f(10))
this function basically goes from n to 1 and each time it adds the current n, in the end, it returns the sum of n n - 1 ... 1
