Write a program to find all happy numbers from 1 to N.
Happy Number: A happy number is a number that eventually reaches 1 when replaced by the sum of the square of each digit
Example 1:
Input :n=14
Output: [1, 7, 10, 13]
Approach:
Java
import java.util.ArrayList;import java.util.List;public class HappyNumber1ToN {public static void main(String[] args) {int num = 14;List<Integer> allHappy = checkHappyNumber1ToN(num);System.out.println("All Happy Number are " + allHappy);}// Method for check all Happy numberprivate static List<Integer> checkHappyNumber1ToN(int num) {// create list for hold numberList<Integer> allHa = new ArrayList<Integer>();// iterate from 1 to numfor (int i = 1; i <= num; i++) {// check current number is happyif (isHappy(i))allHa.add(i);}return allHa;}public static boolean isHappy(int n) {int prev = n;// sum of given numberint next = sumOfSquareDigits(n);// iterate untill both equalwhile (prev != next) {// previuos sumprev = sumOfSquareDigits(prev);// next sumnext = sumOfSquareDigits(sumOfSquareDigits(next));if (next == 1)return true;}return prev == 1;}// method to find the each digit square sumstatic int sumOfSquareDigits(int num) {int sum = 0;while (num > 0) {int digit = num % 10;sum += digit * digit;num = num / 10;}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the each digit square sumint sumOfSquareDigits(int num){int sum = 0;while (num > 0) {int digit = num % 10;sum += digit * digit;num = num / 10;}return sum;}//function to check happy numberbool isHappy(int n) {int prev = n;// sum of given numberint next = sumOfSquareDigits(n);// iterate untill both equalwhile (prev != next) {// previuos sumprev = sumOfSquareDigits(prev);// next sumnext = sumOfSquareDigits(sumOfSquareDigits(next));if (next == 1)return true;}return prev == 1;}//function to find all Happy number//till given numbervector<int> checkHappyNumber1ToN(int num){// create vector to hold//the happy numbervector<int> allHa ;// iterate from 1 to numfor (int i = 1; i <= num; i++) {// check current number is happyif (isHappy(i))allHa.push_back(i);}return allHa;}int main(){int num = 14;vector<int> allHappy = checkHappyNumber1ToN(num);cout<<"All Happy Number are ";for(int i=0;i<allHappy.size();i++)cout<<allHappy[i]<<" ";return 0;}
No comments:
Post a Comment