Write a program to Check the perfect number.
Perfect Number: A number is said to be perfect if the sum of divisors of a number except self is equal to the number itself
Example 1:
Input: num = 6
Output: Number is perfect.
Example 2:
Input: num = 10
Output: Not a perfect number.
Approach:
Java
public class PerfectNumber {public static void main(String[] args) {int num = 6;if (isPerfectNumber(num))System.out.println("Number is perfect");elseSystem.out.println("Not a perfect Number");}private static boolean isPerfectNumber(int num) {int sum = 0;for (int i = 1; i * i <= num; i++) {if (num % i == 0) {if (num / i == i && i != num)sum += i;else {if (num / i != num)sum += num / i;if (i != num)sum += i;}}}// sum of all divisors except it-self is// same as the number thenif (sum == num)return true;elsereturn false;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check the given//number is perfect or notbool isPerfectNumber(int num){int sum = 0;for (int i = 1; i * i <= num; i++){if (num % i == 0){if (num / i == i && i != num)sum += i;else{if (num / i != num)sum += num / i;if (i != num)sum += i;}}}//sum of all divisors except itselt is//same as the number thenif (sum == num)return true;elsereturn false;}int main(){int num = 6;if (isPerfectNumber(num))cout << "Number is perfect\n";elsecout << "Not a perfect Number\n";return 0;}//Time Complexity: O(sqrt(n))//Space Complexity:O(1)
C
#include <stdio.h>#include <stdbool.h>//function to check the given//number is perfect or notbool isPerfectNumber(int num){int sum = 0;for (int i = 1; i * i <= num; i++){if (num % i == 0){if (num / i == i && i != num)sum += i;else{if (num / i != num)sum += num / i;if (i != num)sum += i;}}}//sum of all divisors except it-self is//same as the number thenif (sum == num)return true;elsereturn false;}int main(){int num = 6;if (isPerfectNumber(num)){printf("Number is perfect\n");}else{printf("Not a perfect Number\n");}return 0;}//Time Complexity: O(sqrt(n))//Space Complexity:O(1)
No comments:
Post a Comment