Skip to content

Refactor Happy Number and Factorial Recursion, Remove Duplicate BubbleSort.py #447

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions C++/factorial_recursion.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
#include <iostream>
using namespace std;

int factorial(int n) {

// single line to find factorial
return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
long factorial(int n) {
if(n==1){
return 1; //1! is 1
}
if(n==0){
return 1; //0! is 1
}
return n * factorial(n-1);
/*
n! is the same as n * (n-1)!
n! equals n * (n-1) * (n-2)... 3 * 2 * 1
(n-1)! equals (n-1) * (n-2)... 3 * 2 * 1
(n-1)! * n equals n! and also equal to n * (n-1) * (n-2)... 3 * 2 * 1
*/
}

int main() {
Expand Down
62 changes: 43 additions & 19 deletions C++/happy number.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,52 @@ Example 1:

#include <iostream>
using namespace std;
int find(int n)
{

int sum=0,r;
while(n!=0)
{
r=n%10;
sum=sum+(r*r);
n=n/10;


int Sods(int n){ // Finds Square Digital Sum
int Sum = 0;
while(n!=0){
int mod = (n%10);
Sum += mod*mod;
n = n/10;
}

if ((sum==1)||(sum==7))
{
return 1;

return Sum;
}
bool find(int n)
{
/*
Tortise Hare Explanation:
we have two variables Slow and Fast and a function Sods which calculates the sum of squares of digits of the input number.
Each Iteration, We Run fast through Sods twice and run Slow through Sods once.
If we make Fast update 2 times as fast as slow, then we will be able to find any cycle and if Fast is ever 1, then we know that the number is happy.
Example:
Test=2
Fast | Slow
-----+-----
16 | 4
58 | 16
145 | 37
20 | 58
16 | 89
58 | 145
145 | 42
20 | 20
Since Fast is equal to Slow, 2 is an Unhappy Number
Cycle: 2→4→16→37→58→89→145→42→20→4→16...
*/
int Fast = Sods(Sods(n));
int Slow = Sods(n);
if(Fast == 1){
return true; // Edge Case of n=1 which makes the while loop never happen but still is happy.
}
else if((sum==2)||(sum==3)||(sum==4)||(sum==5)||(sum==6)||(sum==8)||(sum==9))
{
return 0;
while(Fast != Slow){
if(Fast == 1){
return true;
}
Fast = Sods(Sods(Fast));
Slow = Sods(Slow);
}
else
find(sum);
return false;
}
int main()
{
Expand Down
20 changes: 0 additions & 20 deletions DSA/DSA-python/Sorting Algo/BubbleSort.py

This file was deleted.