Write a program to identify if the character is a vowel or consonant
const isVowel = (character) => { const char = character.toLowerCase(); return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u'; }; const checkCharacterType = (character) => { const char = character.toLowerCase(); if (char >= 'a' && char <= 'z') { const type = isVowel(char) ? "vowel" : "consonant"; console.log(`${character} is a ${type}.`); } else { console.log(`${character} is not a letter.`); } }; // Test cases checkCharacterType('a'); // Output: a is a vowel. checkCharacterType('B'); // Output: B is a consonant. checkCharacterType('3'); // Output: 3 is not a letter. checkCharacterType('z'); // Output: z is a consonant. checkCharacterType('E'); // Output: E is a vowel.
def is_vowel(character): char = character.lower() return char in ['a', 'e', 'i', 'o', 'u'] def check_character_type(character): char = character.lower() if char.isalpha(): # Check if the character is a letter if is_vowel(char): print(f"{character} is a vowel.") else: print(f"{character} is a consonant.") else: print(f"{character} is not a letter.") # Test cases check_character_type('a') # Output: a is a vowel. check_character_type('B') # Output: B is a consonant. check_character_type('3') # Output: 3 is not a letter. check_character_type('z') # Output: z is a consonant. check_character_type('E') # Output: E is a vowel.
Write a program to identify if the character is an alphabet or not
const isAlphabet = (character) => { const char = character.toLowerCase(); return char >= 'a' && char <= 'z'; }; // Test cases console.log(isAlphabet('a')); // Output: true console.log(isAlphabet('B')); // Output: true console.log(isAlphabet('3')); // Output: false console.log(isAlphabet('@')); // Output: false console.log(isAlphabet(' ')); // Output: false
def is_alphabet(character): # Check if the character is an alphabet return character.isalpha() # Get user input char = input("Enter a character: ") # Check if the input character is an alphabet if is_alphabet(char): print(f"{char} is an alphabet.") else: print(f"{char} is not an alphabet.")
Write a program to find ASCII values of a character
const findASCII = (character) => { // Using charCodeAt() to get the ASCII value return character.charCodeAt(0); }; // Example usage: const userInput = prompt("Enter a character:"); const character = userInput.charAt(0); // Extract the first character if (character.length === 1) { const asciiValue = findASCII(character); console.log(`The ASCII value of '${character}' is ${asciiValue}.`); } else { console.log("Please enter a valid single character."); }
def find_ascii(character): # Using ord() to get the ASCII value return ord(character) # Example usage: character = input("Enter a character: ") if len(character) == 1: ascii_value = find_ascii(character) print(f"The ASCII value of '{character}' is {ascii_value}.") else: print("Please enter a valid single character.")
Write a program to find Number of digits in an integer
const countDigits = (num) => { // Convert number to string and remove any leading/trailing whitespace const numStr = String(num).trim(); // Return the length of the string (number of digits) return numStr.length; }; // Example usage: const number = 12345; const digitCount = countDigits(number); console.log(`Number of digits in ${number} is ${digitCount}`);
def count_digits(num): # Convert number to string and strip any leading/trailing whitespace num_str = str(num).strip() # Return the length of the string (number of digits) return len(num_str) # Example usage: number = 12345 digit_count = count_digits(number) print(f"Number of digits in {number} is {digit_count}")
Write a program to find Factorial of number
const factorialRecursive = (n) => { if (n < 0) { return NaN; // Factorial is not defined for negative numbers } if (n === 0 || n === 1) { return 1; } else { return n * factorialRecursive(n - 1); } }; // Example usage: const number = 5; const factorial = factorialRecursive(number); console.log(`Factorial of ${number} is ${factorial}`);
def factorial_recursive(n): # Base case: factorial of 0 or 1 is 1 if n == 0 or n == 1: return 1 # Recursive case: n * factorial of (n-1) else: return n * factorial_recursive(n - 1) # Example usage: number = 5 factorial = factorial_recursive(number) print(f"Factorial of {number} is {factorial}")
Write a program to find Fibonacci series up to n
const fibonacciSeries = (n) => { // Initialize an array to store Fibonacci sequence const fib = [0, 1]; // Check for invalid input if (n <= 0) { return []; } else if (n === 1) { return [0]; } // Generate Fibonacci sequence for (let i = 2; i < n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } // Return the generated Fibonacci sequence return fib; }; // Example usage: const n = 10; const fibonacciSequence = fibonacciSeries(n); console.log(`Fibonacci series up to ${n}:`, fibonacciSequence);
def fibonacci_series(n): # Initialize an array to store Fibonacci sequence fib = [0, 1] # Check for invalid input if n <= 0: return [] elif n == 1: return [0] # Generate Fibonacci sequence for i in range(2, n): fib.append(fib[-1] + fib[-2]) # Return the generated Fibonacci sequence return fib # Example usage: n = 10 fibonacci_sequence = fibonacci_series(n) print(f"Fibonacci series up to {n}: {fibonacci_sequence}")
Write a program to identify of the a number is positive or negative
const identifyNumber = (num) => { if (num > 0) { return `${num} is positive.`; } else if (num < 0) { return `${num} is negative.`; } else { return `${num} is zero.`; } }; // Example usage: const number1 = 10; const number2 = -5; const number3 = 0; console.log(identifyNumber(number1)); // Output: 10 is positive. console.log(identifyNumber(number2)); // Output: -5 is negative. console.log(identifyNumber(number3)); // Output: 0 is zero.
def identify_number(num): if num > 0: return f"{num} is positive." elif num < 0: return f"{num} is negative." else: return f"{num} is zero." # Example usage: number1 = 10 number2 = -5 number3 = 0 print(identify_number(number1)) # Output: 10 is positive. print(identify_number(number2)) # Output: -5 is negative. print(identify_number(number3)) # Output: 0 is zero.
Write a program to find sum of digits of a number
const sumOfDigits = (number) => { // Convert number to string to iterate over each digit const numStr = String(number); // Initialize sum variable let sum = 0; // Iterate over each character in the string representation of the number for (let digit of numStr) { // Convert digit back to number and add to sum sum += parseInt(digit, 10); } return sum; }; // Example usage: const number = 12345; const digitSum = sumOfDigits(number); console.log(`Sum of digits of ${number} is ${digitSum}`);
def sum_of_digits(number): # Convert number to string to iterate over each digit num_str = str(number) # Initialize sum variable digit_sum = 0 # Iterate over each character in the string representation of the number for digit in num_str: # Convert digit back to integer and add to sum digit_sum += int(digit) return digit_sum # Example usage: number = 12345 digit_sum = sum_of_digits(number) print(f"Sum of digits of {number} is {digit_sum}")
Write a program to find sum of N natural numbers
const sumOfNNaturalNumbers = (n) => { // Check if n is a positive integer if (n <= 0 || !Number.isInteger(n)) { return "Invalid input. Please enter a positive integer."; } // Calculate sum of first n natural numbers const sum = (n * (n + 1)) / 2; return sum; }; // Example usage: const N = 10; const sum = sumOfNNaturalNumbers(N); console.log(`Sum of first ${N} natural numbers is ${sum}`);
def sum_of_n_natural_numbers(n): # Check if n is a positive integer if n <= 0 or not isinstance(n, int): return "Invalid input. Please enter a positive integer." # Calculate sum of first n natural numbers sum_n = (n * (n + 1)) // 2 return sum_n # Example usage: N = 10 sum_result = sum_of_n_natural_numbers(N) print(f"Sum of first {N} natural numbers is {sum_result}")
Write a program to find sum of numbers in a given range
const sumInRange = (start, end) => { // Initialize sum variable let sum = 0; // Swap start and end if start is greater than end if (start > end) { [start, end] = [end, start]; } // Iterate over the range from start to end (inclusive) for (let i = start; i <= end; i++) { sum += i; } return sum; }; // Example usage: const start = 1; const end = 10; const result = sumInRange(start, end); console.log(`Sum of numbers from ${start} to ${end} is ${result}`);
def sum_in_range(start, end): # Initialize sum variable sum_result = 0 # Swap start and end if start is greater than end if start > end: start, end = end, start # Iterate over the range from start to end (inclusive) for num in range(start, end + 1): sum_result += num return sum_result # Example usage: start = 1 end = 10 result = sum_in_range(start, end) print(f"Sum of numbers from {start} to {end} is {result}")
Write a program to reverse a given number
const reverseNumber = (number) => { let reversedNum = 0; let num = Math.abs(number); // Take the absolute value of the number while (num > 0) { // Multiply the current reversed number by 10 and add the last digit of num reversedNum = reversedNum * 10 + num % 10; // Remove the last digit from num num = Math.floor(num / 10); } // Apply the sign of the original number to the reversed number if (number < 0) { reversedNum = -reversedNum; } return reversedNum; }; // Example usage: const number = 12345; const reversedNumber = reverseNumber(number); console.log(`Original number: ${number}`); console.log(`Reversed number: ${reversedNumber}`);
def reverse_number(number): reversed_num = 0 num = abs(number) # Take the absolute value of the number while num > 0: # Multiply the current reversed number by 10 and add the last digit of num reversed_num = reversed_num * 10 + num % 10 # Remove the last digit from num num = num // 10 # Apply the sign of the original number to the reversed number if number < 0: reversed_num = -reversed_num return reversed_num # Example usage: number = 12345 reversed_number = reverse_number(number) print(f"Original number: {number}") print(f"Reversed number: {reversed_number}")
Write a program to find LCM of two numbers
const gcd = (a, b) => { // Calculate the greatest common divisor (GCD) using Euclid's algorithm while (b !== 0) { let temp = b; b = a % b; a = temp; } return a; }; const lcm = (a, b) => { // Calculate the LCM using the formula: LCM(a, b) = (a * b) / GCD(a, b) return (a * b) / gcd(a, b); }; // Example usage: const num1 = 12; const num2 = 18; const result = lcm(num1, num2); console.log(`LCM of ${num1} and ${num2} is ${result}`);
def gcd(a, b): # Calculate the greatest common divisor (GCD) using Euclid's algorithm while b != 0: a, b = b, a % b return a def lcm(a, b): # Calculate the LCM using the formula: LCM(a, b) = (a * b) / GCD(a, b) return (a * b) // gcd(a, b) # Example usage: num1 = 12 num2 = 18 result = lcm(num1, num2) print(f"LCM of {num1} and {num2} is {result}")
Write a program to identify if the number is strong number of not
const factorial = (n) => { if (n === 0 || n === 1) { return 1; } return n * factorial(n - 1); }; const isStrongNumber = (number) => { let num = number; let sum = 0; // Calculate factorial of each digit and sum them while (num > 0) { let digit = num % 10; sum += factorial(digit); num = Math.floor(num / 10); } // Check if sum of factorials equals the original number return sum === number; }; // Example usage: const num = 145; const result = isStrongNumber(num); console.log(`${num} ${result ? 'is' : 'is not'} a strong number`);
def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n - 1) def is_strong_number(number): num = number digit_sum = 0 # Calculate factorial of each digit and sum them while num > 0: digit = num % 10 digit_sum += factorial(digit) num //= 10 # Check if sum of factorials equals the original number return digit_sum == number # Example usage: num = 145 result = is_strong_number(num) print(f"{num} {'is' if result else 'is not'} a strong number")
Write a program to identify if the number is Perfect number or not
const isPerfectNumber = (number) => { if (number <= 1) { return false; } let sum = 0; // Find all divisors of the number for (let i = 1; i <= Math.floor(number / 2); i++) { if (number % i === 0) { sum += i; } } // Check if sum of divisors equals the number return sum === number; }; // Example usage: const num = 28; const result = isPerfectNumber(num); console.log(`${num} ${result ? 'is' : 'is not'} a perfect number`);
def is_perfect_number(number): if number <= 1: return False sum_of_divisors = 0 # Find all divisors of the number for i in range(1, number): if number % i == 0: sum_of_divisors += i # Check if sum of divisors equals the number return sum_of_divisors == number # Example usage: num = 28 result = is_perfect_number(num) print(f"{num} {'is' if result else 'is not'} a perfect number")
Write a program to find Power of number (recursive)
const power = (base, exponent) => { // Base case: if exponent is 0, return 1 if (exponent === 0) { return 1; } // Recursive case: compute base^exponent // If exponent is positive if (exponent > 0) { return base * power(base, exponent - 1); } // If exponent is negative else { return (1 / base) * power(base, exponent + 1); } }; // Example usage: const base = 2; const exponent = 3; const result = power(base, exponent); console.log(`${base} raised to the power of ${exponent} is ${result}`);
def power(base, exponent): # Base case: if exponent is 0, return 1 if exponent == 0: return 1 # Recursive case: compute base^exponent # If exponent is positive if exponent > 0: return base * power(base, exponent - 1) # If exponent is negative else: return (1 / base) * power(base, exponent + 1) # Example usage: base = 2 exponent = 3 result = power(base, exponent) print(f"{base} raised to the power of {exponent} is {result}")
Write a program to find the Factors of a number
const findFactors = (number) => { if (number <= 0) { return 'Number should be a positive integer greater than zero.'; } const factors = []; // Iterate from 1 to square root of number for (let i = 1; i <= Math.floor(Math.sqrt(number)); i++) { if (number % i === 0) { factors.push(i); // Add i as a factor // If i is not the square root of number, add number / i as a factor if (i !== number / i) { factors.push(number / i); } } } return factors.sort((a, b) => a - b); // Sort factors in ascending order }; // Example usage: const num = 28; const result = findFactors(num); console.log(`Factors of ${num}:`, result);
import math def find_factors(number): if number <= 0: return 'Number should be a positive integer greater than zero.' factors = [] # Iterate from 1 to square root of number for i in range(1, math.isqrt(number) + 1): if number % i == 0: factors.append(i) # Add i as a factor # If i is not the square root of number, add number // i as a factor if i != number // i: factors.append(number // i) factors.sort() # Sort factors in ascending order return factors # Example usage: num = 28 result = find_factors(num) print(f"Factors of {num}: {result}")
Write a program to add two fractions
const gcd = (a, b) => { // Calculate the greatest common divisor (GCD) using Euclid's algorithm while (b !== 0) { let temp = b; b = a % b; a = temp; } return a; }; const addFractions = (numerator1, denominator1, numerator2, denominator2) => { // Calculate the least common multiple (LCM) of denominators const lcm = (denominator1 * denominator2) / gcd(denominator1, denominator2); // Compute the new numerators const newNumerator1 = numerator1 * (lcm / denominator1); const newNumerator2 = numerator2 * (lcm / denominator2); // Calculate the sum of numerators const sumNumerator = newNumerator1 + newNumerator2; // Simplify the result if necessary using GCD const commonGcd = gcd(sumNumerator, lcm); // Return the simplified fraction return [sumNumerator / commonGcd, lcm / commonGcd]; }; // Example usage: const numerator1 = 1; const denominator1 = 2; const numerator2 = 1; const denominator2 = 3; const [resultNumerator, resultDenominator] = addFractions(numerator1, denominator1, numerator2, denominator2); console.log(`Result of ${numerator1}/${denominator1} + ${numerator2}/${denominator2} = ${resultNumerator}/${resultDenominator}`);
def gcd(a, b): # Calculate the greatest common divisor (GCD) using Euclid's algorithm while b != 0: a, b = b, a % b return a def add_fractions(numerator1, denominator1, numerator2, denominator2): # Calculate the least common multiple (LCM) of denominators lcm = (denominator1 * denominator2) // gcd(denominator1, denominator2) # Compute the new numerators new_numerator1 = numerator1 * (lcm // denominator1) new_numerator2 = numerator2 * (lcm // denominator2) # Calculate the sum of numerators sum_numerator = new_numerator1 + new_numerator2 # Simplify the result if necessary using GCD common_gcd = gcd(sum_numerator, lcm) # Return the simplified fraction return sum_numerator // common_gcd, lcm // common_gcd # Example usage: numerator1 = 1 denominator1 = 2 numerator2 = 1 denominator2 = 3 result_numerator, result_denominator = add_fractions(numerator1, denominator1, numerator2, denominator2) print(f"Result of {numerator1}/{denominator1} + {numerator2}/{denominator2} = {result_numerator}/{result_denominator}")
Write a program to find Greatest of two numbers
const findGreatest = (num1, num2) => { if (num1 > num2) { return num1; } else { return num2; } }; // Example usage: const num1 = 10; const num2 = 20; const greatest = findGreatest(num1, num2); console.log(`The greatest number between ${num1} and ${num2} is: ${greatest}`);
def find_greatest(num1, num2): if num1 > num2: return num1 else: return num2 # Example usage: num1 = 10 num2 = 20 greatest = find_greatest(num1, num2) print(f"The greatest number between {num1} and {num2} is: {greatest}")
Write a program to find Greatest of three numbers
const findGreatestOfThree = (num1, num2, num3) => { let greatest = num1; // Assume num1 is the greatest initially if (num2 > greatest) { greatest = num2; } if (num3 > greatest) { greatest = num3; } return greatest; }; // Example usage: const num1 = 10; const num2 = 20; const num3 = 15; const greatest = findGreatestOfThree(num1, num2, num3); console.log(`The greatest number among ${num1}, ${num2}, and ${num3} is: ${greatest}`);
def find_greatest_of_three(num1, num2, num3): greatest = num1 # Assume num1 is the greatest initially if num2 > greatest: greatest = num2 if num3 > greatest: greatest = num3 return greatest # Example usage: num1 = 10 num2 = 20 num3 = 15 greatest = find_greatest_of_three(num1, num2, num3) print(f"The greatest number among {num1}, {num2}, and {num3} is: {greatest}")
Write a program to identify if the number is Armstrong number or not
const isArmstrongNumber = (number) => { // Convert number to string to iterate over each digit const numStr = String(number); const n = numStr.length; // Find number of digits (n) let sum = 0; // Calculate sum of each digit raised to the power of n for (let digit of numStr) { sum += Math.pow(parseInt(digit), n); } // Check if sum equals the original number return sum === number; }; // Example usage: const num = 153; const result = isArmstrongNumber(num); console.log(`${num} is ${result ? 'an Armstrong number' : 'not an Armstrong number'}`);
def is_armstrong_number(number): num_str = str(number) n = len(num_str) sum = 0 # Calculate sum of each digit raised to the power of n for digit in num_str: digit_int = int(digit) power_result = 1 # Multiply digit_int by itself n times for i in range(n): power_result *= digit_int sum += power_result return sum == number # Example usage: num = 153 result = is_armstrong_number(num) print(f"{num} is {'an Armstrong number' if result else 'not an Armstrong number'}")
Write a program to identify if the number is prime number or not
const isPrimeNumber = (number) => { // Check if number is less than or equal to 1 if (number <= 1) { return false; } // Check for numbers from 2 to half of the number for (let i = 2; i <= number / 2; i++) { // If number is divisible by any i, it's not prime if (number % i === 0) { return false; } } // If no divisors other than 1 and itself, it's prime return true; }; // Example usage: const num = 29; const result = isPrimeNumber(num); console.log(`${num} is ${result ? 'a prime number' : 'not a prime number'}`);
def is_prime_number(number): # Check if number is less than or equal to 1 if number <= 1: return False # Check for numbers from 2 to half of the number for i in range(2, number // 2 + 1): # If number is divisible by any i, it's not prime if number % i == 0: return False # If no divisors other than 1 and itself, it's prime return True # Example usage: num = 29 result = is_prime_number(num) print(f"{num} is {'a prime number' if result else 'not a prime number'}")
Write a program to identify if the number is Palindrome or not
const isPalindrome = (number) => { // Convert number to string const numStr = String(number); // Reverse the string const reversedNumStr = numStr.split('').reverse().join(''); // Check if original number is equal to reversed number return numStr === reversedNumStr; }; // Example usage: const num1 = 121; const num2 = 12321; const num3 = 12345; console.log(`${num1} is ${isPalindrome(num1) ? 'a palindrome' : 'not a palindrome'}`); console.log(`${num2} is ${isPalindrome(num2) ? 'a palindrome' : 'not a palindrome'}`); console.log(`${num3} is ${isPalindrome(num3) ? 'a palindrome' : 'not a palindrome'}`);
def is_palindrome(number): if number < 0: return False # Negative numbers cannot be palindromes original_number = number reversed_number = 0 # Reverse the number while number > 0: remainder = number % 10 reversed_number = reversed_number * 10 + remainder number = number // 10 # Check if original number is equal to reversed number return original_number == reversed_number # Example usage: num1 = 121 num2 = 12321 num3 = 12345 print(f"{num1} is {'a palindrome' if is_palindrome(num1) else 'not a palindrome'}") print(f"{num2} is {'a palindrome' if is_palindrome(num2) else 'not a palindrome'}") print(f"{num3} is {'a palindrome' if is_palindrome(num3) else 'not a palindrome'}")