JavaScript:
var UI; // Number entered by user
var TV; // Number value to be used in calculations
var HITS; // Counter
var DD; // Division denominator
UI = window.prompt("Enter a whole number to be tested as a prime number", "0");
TV = parseInt("UI", [10]);
HITS = 0;
DD = TV;
while (DD > 0) {
if (TV % DD == 0) {
HITS++
}
HITS--
}
window.document.write(+UI + " is ");
if (HITS > 2) {
window.document.write(" not");
}
window.document.write(" a prime number.");
Can anyone tell me what I'm doing wrong? Everything runs except when it isn't a prime number it the "not" string won't come up. Any help is greatly appreciated.
UI = window.prompt("Enter a whole number to be tested as a prime number", "0");
TV = parseInt(UI,10);
HITS = 0;
DD = TV;
while(DD>0) {
if (TV%DD===0) {
HITS++; }
DD--;
}
I changed this much of and it works now.
//FOR user FOON
PrimeNumber=function(){
var d, l, primelist;
_isPrimeNumber = function(n){
var result = true;
_setVariables(n);
while( d < l ){
if(n % d == 0){
result = false;
break;
}
do{
d = d + 1;
}while(!_check(d));
primelist.push(d);
l = n/d;
}
return result;
};
_getAllPrimeTill = function(n){
_setVariables(n);
while( d < n ){
d = d + 1;
if(_check(d)){
primelist.push(d);
}
}
return primelist;
};
_setVariables = function(n){
d=2;
l=n/2;
primelist = new Array();
primelist.push(d);
};
_check = function(n){
var result = true;
for(var i = 0; i < primelist.length; i++){
if(n % primelist[i] == 0 ){
result = false;
break;
}
}
return result;
};
return {
isPrimeNumber :_isPrimeNumber,
getAllPrimeTill : _getAllPrimeTill
};
}();
You have:
DD = TV;
// The value of DD is tested, but not modified in the loop
while(DD>0) {
// This part is irrelevant to the test
if (TV%DD == 0) {
HITS++
}
HITS--
}
DD is not modified in the loop, so if the condition is true or false, it will always be true or false. So if DD is any value greater than zero, the condition is always true.
import java.util.ArrayList;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*if you want to find all prime numbers between 2 and n, change loop "while( d < l ){" to "while( d < n ){" and you will get al prime numbers in primelist.
*/
/**
*
* #author hp
*/
public class PrimeNumber {
public static void main(String[] args) {
String result = " IS A PRIME NUMBER";
int n = 127;
int d = 2;
int l = n / 2;
List <Integer> primelist = new ArrayList<Integer>();
while( d < l ){
if(n % d == 0){
//System.out.println();
//System.out.println(n + " can be divided by " + d);
//System.out.println(d + " * " + (n / d) + " = " + n);
result = " IS NOT A PRIME NUMBER";
break;
}
do{
d = d + 1;
}while(!isPrimeNumber(d,primelist));
//System.out.print(d + ", ");
primelist.add(new Integer(d));
l = n/d;
}
//System.out.println();
System.out.println(n + result);
}
private static boolean isPrimeNumber(int n, List <Integer> primelist){
boolean result = true;
for(Integer i : primelist){
if(n % i.intValue() == 0 ){
result = false;
}
}
return result;
}
}
Related
while (a) {
b.push(a % 10);
a = Math.floor(a / 10);
if (b == 7) {
n = n + 1;
}
console.log("<br><br>number of 7's:" + n);
}
This is what I have come up with. The output is one of the numbers has seven; if not, then zero. I want the program to count the number of times seven appears in a number.
You can convert the number to a string, and then count how many times a character = 7:
let n = 7326577
let cnt = 0;
let strN = '' + n;
for(let c of strN)
if(c == '7')
cnt ++
console.log('Number of 7\'s in number: ' + cnt)
Following you approach you need to store the last digit to a different variable and use that for checking if it is a 7
var a = 709728457;
var b = [];
var n = 0;
while (a) {
const lastDigit = a % 10;
b.push(lastDigit); // if you still need to store all digits
a = Math.floor(a / 10);
if (lastDigit == 7) {
n = n + 1;
}
}
console.log("number of 7's:" + n);
var a = 7686774737
var no = String(a).split('').filter(e=>e==7).length;
console.log(no)
can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/
I want to implement a function in Google Spreadsheet using JavaScript. I have:
var s1 = "000000000000"; // (12 zeros)
var n1 = 1;
I have a third number between 1 and 12. If my number is 6 the result would need to be: 111111000000. If my number is 8 the result would need to be 111111110000.
So far I got stuck here:
function REP(b1) {
var s1 = "000000000000" ;
var n1 = 1;
if (b1 >=1 && b1 <= 12) {
return s1.split("0").join(n1) ;
}
else{
return "no value" ;
}
}
I prefer a simple approach:
function rep(b1) {
var s1 = "000000000000";
var s2 = "111111111111";
if (b1 >=1 && b1 <= 12) {
return s2.slice(0, b1) + s1.slice(b1);
} else {
return "no value";
}
}
console.log(rep(6)); // 111111000000
console.log(rep(8)); // 111111110000
const replacement = "1"
function replaceZeros(n) {
var result = "000000000000"
while (n --> 0) { // it actually mean `n-- > 0`, but it looks cooler that way
result = result.replace(/0/, replacement)
}
return result
}
This simply replaces the first 0 in the string n times.
See demo on JS Bin.
interesting. i would try
function REP(b1) {
var ret = ""
for (var i = 0; i < 12; i++){
if(i < b1){
ret += "1";
}
else{
ret += "0";
}
}
return ret;
}
hrm... there might be a nicer way though...
EDIT: oh yeah, i think you can do:
function REP(b1) {
if(isNaN(b1) || b1 < 1 || b1 > 12){
return 'no answer';
}
return "1".repeat(b1) + "0".repeat(12-b1);
}
you can use Array.join to repeat characters
see following example...
alert(REP(6));
function REP(b1) {
var s1 = "000000000000";
var n1 = 1;
if (b1 >=1 && b1 <= 12) {
return (Array(b1 + 1).join(n1) + s1).substr(0, 12);
} else{
return "no value" ;
}
}
Not sure how performant this is but here's a regex method.
function REP(b1) {
if (b1 < 1 || b1 > 12) return 'no value';
var rx = new RegExp('0{' + b1 + '}');
return '000000000000'.replace(rx, Array(b1 + 1).join(1));
}
DEMO
I'm sending the number/string 0.001 to a the function below:
SignificantFigures = 4;
function LimitNumberOfDigits(num) {
var tempStr = "";
if (isNaN(num))
return "\xD8";
else{
if (parseFloat(num) === 0 || (num.toString().indexOf('.') === -1 && parseInt(num) < 9999) || num.toString().length <= 4) {
return num;
}
tempStr = parseFloat(num).toPrecision(SignificantFigures);
if (tempStr.indexOf("e") > -1) {
var startE = tempStr.indexOf("e");
var endE = 0;
for (var i = startE +2 ; i < tempStr.length; i++ ) { // + to ignore e and sign (+ or - )
if(parseInt(tempStr[i], 10) > 0) {
endE = i;
}else {
break;
}
}
if (startE + 2 === endE) {
var pow = tempStr[endE];
} else {
var pow = tempStr.substring(startE +2 ,endE);
}
return tempStr.substring(0,startE) + "*10<sup>"+ pow +"</sup>";
}else {
return parseFloat(num).toPrecision(SignificantFigures);
}
}
}
When im sending 0.2 or even 0.11 im getting like 0.2000 and 0.1100.
The issue here is the toPrecision acts like ToFixed.
Ideas?
EDIT
What i want? simple as that, if a numbers needs to be changed e.g 0.012312312041 it should be 0.0123 , numbers like 0.12 or 28 should stay the same.
I need to a function to convert an integer to the equivalent alpha ordered list index. For example:
1 = a
2 = b
.
.
.
26 = z
27 = aa
28 = ab
.
.
etc.
Currently I have the following which almost works but there's a small logic error somewhere that makes it not quite get it right (it goes ax, ay, bz, ba, bb, bc...):
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = '',
place,
num,
i;
for ( i = 0; Math.pow(alphaMax, i) < int; i++ ) {
place = Math.pow(alphaMax, i);
num = Math.floor( ( int / place ) % alphaMax);
asciiCode = ( num == 0 ? alphaMax : num ) + asciiStart - 1;
char = String.fromCharCode(asciiCode);
alpha = char + alpha;
}
return alpha;
}
for (i = 1; i < 300; i++) {
console.log( i + ': ' + intToAlpha(i) );
}
This function is used in NVu/Kompozer/SeaMonkey Composer, with a small tweak to generate lower case directly:
function ConvertArabicToLetters(num)
{
var letters = "";
while (num > 0) {
num--;
letters = String.fromCharCode(97 + (num % 26)) + letters;
num = Math.floor(num / 26);
}
return letters;
}
You need to make sure that you use the correct value when taking the mod.
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = "";
while(int > 0) {
char = String.fromCharCode(asciiStart + ((int-1) % alphaMax));
alpha = char + alpha;
int = Math.floor((int-1)/26);
}
return alpha;
}
A while back I needed the same thing in SQL, so I asked (and answered) the question Multi-base conversion - using all combinations for URL shortener.
The thing that is making it complicated is that it's not a straight base conversion, as there is no character representing the zero digit.
I converted the SQL function into Javascript:
function tinyEncode(id) {
var code, value, adder;
var chars = 'abcdefghijklmnopqrstuvwxyz';
if (id <= chars.length) {
code = chars.substr(id - 1, 1);
} else {
id--;
value = chars.length;
adder = 0;
while (id >= value * (chars.length + 1) + adder) {
adder += value;
value *= chars.length;
}
code = chars.substr(Math.floor((id - adder) / value) - 1, 1);
id = (id - adder) % value;
while (value > 1) {
value = Math.floor(value / chars.length);
code += chars.substr(Math.floor(id / value), 1);
id = id % value;
}
}
return code;
}
Demo: http://jsfiddle.net/Guffa/mstBe/