My goal is to create a program that checks whether the user input is a perfect number or not. It has validation for the numbers entered. If the input IS a perfect number, I'd like to print out each of the divisors. I tried using this method:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
However, I was unable to get the desired effect. I am very new to javascript and am struggling with inserting code in the correct way. Does anyone have a suggestion for how I can get the desired effect? Here is the code I have already written:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
I'd suggest revising your is_perfect() function to return an array of divisors if the number is perfect and null if the number is not perfect. Then the calling code has the divisors available for display when the input is a perfect number.
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
Then:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[Note: In an earlier version of this answer, I had initialized temp to 1 and divisors to [1] and had started the loop at 2, on the theory that 1 is always a divisor. Unfortunately, that's wrong, since 1 is not a proper divisor of 1. The revised version of is_perfect() now returns null for an argument of 1 instead of [1]. An alternative fix would have been to test explicitly for the case number === 1, but that's uglier (if perhaps a tiny bit more efficient, since it avoids one % evaluation).]
so I use 2^(n-1)*(2^n -1) formula (to generate a perfect number) and checking if last digit is 6 or 8 to check if x is perfect number.
Note: It's not perfect 100%
function pn(x) {
x = '' + x
for (var i = 0; i < Infinity; i++) {
perfnumgen = Math.pow(2, i - 1) * (Math.pow(2, i) - 1)
if (x === "" + perfnumgen && (perfnumgen % 10 === 8 || perfnumgen % 10 === 6))
return true
else if (perfnumgen > x)
return false
console.log("" + perfnumgen)
}
}
Related
So I need a tiny bit of help with this code, Some background information: The user inputs a number, the code takes the number and outputs various combinations of numbers that multiply to it.
For example:
Input: 7
Output: (1,7)(7,1).
*But what really happens:
*
Input: 7
Output: (7,1)
I want my code to reverse the numbers as well, so it makes can look like it has two combinations
var input= parseInt(prompt("Please enter a number larger than 1"));
var arr = [];
if(input <= 1) {
console.log("Goodbye!")
}
while(input > 0) {
var arr = [];
var input = parseInt(prompt("Please enter a number larger than 1"));
for (var i = 0; i < input; ++input) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
}
My code just need this tiny bit of problem fixed and the rest will be fine!
Your code has 2 infinite loop because you never change i and always increase input.
also in this line for (var i = 0; i < input; ++input) you never let i to be equal to the input so in your example (input=7) you can not have (7,1) as one of your answers. I think this is what you looking for:
var input = 1;
while(input > 0) {
input = parseInt(prompt("Please enter a number larger than 1"));
if(input > 1) {
var arr = [];
for (var i = 0; i <= input; ++i) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
continue;
}
else{
console.log("Goodbye!");
break;
}
}
I need my code to only accept whole numbers, no decimals and should prompt an error when a decimal gets entered. I don't want a new function , I'm hoping I can just add lines to my function but I don't know what I need to add.
function number_function() {
number = parseInt(prompt('Enter a positive integer:'));
if (number < 0) {
alert('Error! Factorial for negative number does not exist. But I will show you the positive number');
number = number * -1;
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
} else if (number === 0) {
alert("Please enter a number greater than 0");
} else {
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
}
}
number_function();
You can do this to check if the number has decimals
const val = 10.7 % 1;
if (val !== 0) {
console.log('has decimals');
} else {
console.log('has no decimal');
}
JavaScript provides the built-in function Number.isInteger(n)
Quick follow-up question on my previous question. I'd like to add the code to the following to calculate the factorial of a number entered by user in Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
}
while (counter<=numOfLoops)
alert ("The sum of numbers from 1 to " + numbers + "is =" +sum);
}
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
If you are trying to sum up the numbers, consider using arithmetic series formula. If you're trying to get the factorial, the approach is shown below.
If you want to sum using the loop, just change the *= to +=.
While Loop Approach
const fact = (n) => {
let res = 1;
while (n > 0) {
res *= n;
n--;
}
return res;
}
fact(5) // 120
Do While Approach
const fact = (n) => {
let res = 1;
do {
res *= n;
n--;
} while (n > 0)
return res;
}
fact(3) // 6
That should do the trick. :)
Maybe also considering checking for edge cases like if the n is negative.
Good luck.
While Loop:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
Do While:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
do r *= n || 1 // in case of n == 0
while (n--)
return r;
}
complete code
const
msgPrompt_1 = 'Please enter a number from 0 to 100',
msgPrompt_n = 'Try again.... Enter a number 0-100',
fact = n =>
{
let r = 1
while(n) r *= n--
return r
}
let numValue = parseInt(window.prompt(msgPrompt_1, ''), 10)
while(isNaN(numValue) || numValue > 100 || numValue < 0)
{
numValue = parseInt(window.prompt(msgPrompt_n, ''), 10)
}
alert(`factorial value of ${numValue} is = ${fact(numValue)}` )
I have a program that needs to convert integers to binary and decimal. I have the binary portion working but am stuck on the decimal part. I'm trying to use intToFloat but not sure if that's right. Here is the code for the conversion functions.
if (cT[0].checked) {
// to binary
var dval = parseInt(val);
if (isNaN(dval)) {
alert("input value is not a number");
}
else if ((val % 1) !== 0 ) {
alert("number is not a integer");
}
else if (dval < 0) {
alert("Input value must be a positive integer");
}
else {
convertByArray(dval);
}
}
else if (cT[1].checked) {
//to decimal
var dval = parseFloat(val);
if (isNaN(dval)) {
alert("input value is not a number");
}
else if ((val % 1) !== 0 ) {
alert("number is not a integer");
}
else if (dval < 0) {
alert("Input value must be a positive integer");
}
else {
intToFloat(dval);
}
}
else {
alert("Please select a conversion type.");
}
}
function convertByArray(dval) {
var rA = new Array();
var r,i,j;
i=0;
while (dval > 0) {
r = dval % 2;
rA[i] = r;
var nV = (dval - r) / 2;
$("txtCalc").value = $("txtCalc").value + " Decimal " + dval + " divided by 2 = "
+ nV + " w/Remainder of: " + r + "\n";
i += 1;
dval = nV;
}
for(j=rA.length-1; j>= 0; j--) {
$("txtOut").value = $("txtOut").value + rA[j];
}
}
function intToFloat(num, decPlaces) {
return num + '.' + Array(decPlaces + 1).join('0');
}
I need it to show the output of an integer being converted to a decimal and show the value as well, like it already does when it converts to binary.
parseInt(value, fromBase).toString(toBase)
To convert it to binary
parseInt(25,10).toString(2) //<== '25' is the value, 10 is the current base. 2 is the base you want to converted.
To convert it to decimal
parseInt(100011,2).toString(10)
To convert it to float
var num = 203
num.toFixed(6) // asnwer will be 203.000000
I'm having some trouble with the for loop. I have the while loop working properly, but I need help with the nested loop. The concept of loops is fairly new to me and I don't quite understand what I've done here in the code. Any help would be greatly appreciated.
var number = parseInt(window.prompt("Enter number: ", ""));
var divisor;
var check;
var prime = true;
var num;
document.write("The factors of ", number, " are: </br>");
divisor = 1;
while (divisor <= number) {
check = number % divisor;
if (check == 0) {
document.write(divisor, " ");
if ((divisor != 1) && (divisor != number)) {
prime = false;
}
}
divisor = divisor + 1;
}
if (prime == true) {
document.write("<br>The number is prime");
} else {
document.write("<br> The number is composite");
}
Something to get you excited. This program is using for and while to check prime numbers. The for loop is used as an if-check but this will work. You should also try using functions to minimize your code.
var number = parseInt(window.prompt("Enter number: ", ""));
var result = isPrime(number);
function isPrime(number) {
var start = 2;
//USING WHILE
while (start <= Math.sqrt(number)) {
if (number % start++ < 1) return false;
}
return number > 1;
}
//USING FOR
for (;result;){
document.write("<br>The number is prime");
}
if(!result) {
document.write("<br>The number is NOT prime");
}
As a fresh man,I think may you need a break in the while loop,beacause you just check if it is prime once.Just like that:
if((divisor != 1) && (divisor != number)){
prime= false;
break;
}