w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Can you explain this method of finding prime numbers in javascript
It's called the Sieve of Erathestenes and it's an efficient way of finding all prime numbers between zero and some upper limit integer. j = i << 1 This is a bit shift operation. It shifts an integer 1 bit to the left. Because binary is base two, this is equivalent to multiplying by two. In decimal, the equivalent operation would be shifting, say, 1 to the left and bringing in a zero to the right. It's base ten, so you end up with 10 (ten times one.) I don't believe the implementation you show is optimal. The limit to the i value can be lower -- something like sqrt(max). You can easily find some really nice animations online of this algorithm that show you what's going on in quite an intuitive way.

Categories : Javascript

Finding number of k-prime numbers;
The algorithm you are using is know as Sieve of Eratosthenes. It is a well known algorithm for finding prime numbers. Now to answer your questions : 1a) What is the complexity of this code The complexity of your code is O(n log(log n)). For and input of a and b the complexity of your code is O(b log log b). The runtime is due to the fact that you first mark b/2 number then b/3 then b/5 and so on. So your runtime is b * (1/2 + 1/3 + 1/5 + 1/7 + 1/11 + ... + 1/prime_closest_to_b). What we have there is a prime harmonic series which grows asymptotically as ln(ln(b+1)) (see here). Asymptotically the upper bound is: O(b * (1/2 + 1/3 + 1/5 + 1/7 +..)) = O(b) * O(log(log(b+1))) = O(b*log(log(b)) 1b) Can it be done in O(n) This is tricky. I would say that for all practical purposes an O(n

Categories : C

MASM code for finding prime numbers not working
Managed to fix it. Because of my poor placement of debug breakpoints I didn't realize that the edx register is being used properly. However, two other problems were present in my code. Working code is below. Notice the new jmp command right before the prime: tag, and the new reset of testNum before the return. isPrime PROC; checks if a number is prime by dividing out values less than it until it finds one that has a remainder of 0 ;or the test value reaches the number retest: inc testNum mov eax, testPrime cmp eax, testNum je prime mov edx, 0 mov eax, testPrime mov ebx, testNum div ebx mov eax, edx cmp eax, ZERO jg retest mov eax, 1 mov testNum, eax inc testPrime jmp retest prime: mov eax, 1 mov testNum, eax ret isPrime ENDP

Categories : Assembly

Prime numbers not printing in Javascript
The function primes is written to expect an array, but you're passing it an integer. Did you mean fmt(primes(primesarray(k)))? (That does at least print a list of numbers, but I'm afraid many of them are not primes!)

Categories : Javascript

Javascript prime number error?
You are returning the function from inside the forloop. So it never hits the other statements Check Fiddle

Categories : Javascript

Javascript: find first n prime numbers
In your code, array.push[i] (with square brackets) doesn't do what you'd like it to. It leaves the array unchanged and returns undefined. You meant array.push(i) (with parentheses).

Categories : Javascript

How to Pass JSON object to GOJS javascript file from Java/Prime Faces
You can request data from server using an AJAX call and get the data. if that is not an option then you can put the data in a hidden field on the page and then access it in your load() function, like you are doing it in your save() function using document.getElementById.

Categories : Javascript

Why is my program giving me all the non-prime numbers when I ask for prime numbers?
The problem is your loop: while (next_prime + 1 < MAXBYTES*8 && getBit(bit_arr, ++next_prime)) { print_prime(next_prime); } Your keeping printing things while the bit is set (i.e. while you know it's not a prime). So basically, your loop is "print all the numbers I find while looking for the next prime" rather than "look for the next prime in a loop, then print the next prime". I suspect you want something like: next_prime++; // We always want to at least move on once... while (next_prime + 1 < MAXBYTES*8 && getBit(bit_arr, next_prime)) { next_prime++; } print_prime(next_prime); I haven't checked whether that's all that was wrong with the code, but it's certainly an initial thing to fix.

Categories : C

Finding the javascript that changes a DOM element
The approach I use in these situations is to examine the HTML around the area that is being modified, note all possible ways that code could find the appropriate DOM elements (form names, id values, class names, etc...) and then look through the code to find where it might be querying the DOM to find the DOM element that is being changed using one of these identifiers. Since the identifiers can't be obscured, they should be in the code in normal English the same as they appear in the HTML. In addition, you can make a list of all event listeners that are being set in the code and pay particular attention to event listeners on any objects near the one being changed. Since it's a form submission, you can look for the submit event or click event on a form submission button. When you see ev

Categories : Javascript

Finding the value of all H2s on a page with Javascript
If you're using jQuery, you could run something like this $('h2').each({ /* function */ }); Then to append to the .nav container you can run $('h2').each(function() { $('.nav').append($(this).text()) });

Categories : Javascript

Finding properties in a javascript object
If you re-structure your JSON to nest the options/result inside the respective parent it becomes easy to get all the possible options. You would need to change your code to this: $.ajax({ url: "http://www.myurl.com/jsonp.php", type: "GET", dataType: "jsonp", jsonpCallback: "otmjsonp", async: false, success: function (JSON) { $(".result").on("click", function () { var currentResult = $(this).text(); //.result is the line of HTML the user has clicked if (JSON.hasOwnProperty(playerSelection)) { for (var outcome in JSON[playerSelection]) { if (JSON[playerselection].hasOwnProperty(outcome)) { alert("This is the next outcome " + JSON[playerSelection][outcome]); } } } }) } });

Categories : Javascript

javascript finding center of a rotated rectangle
In the situation you describe when there is a problem, the roles of the two dots are reversed: you HAVE the lower one and want to find the upper. Add an if statement to detect this condition, and write a version of your code that recognizes this reversal.

Categories : Javascript

Finding the min first value of a list of pairs of numbers in JavaScript
As Sirko said, you can do that with a simple for loop, comparing each first value with its previous value. You can also do that with the reduce1 array method, to achieve shorter code: var tuples = [[1,2], [2,4], [3,5], [5,2]]; var tupleWithMinFirstValue = tuples.reduce(function(previous, current){ return current[0] < previous[0] ? current : previous; }, [Infinity]); console.log(tupleWithMinFirstValue); http://jsfiddle.net/wAGMX/ 1 The link also provides compatibility info, and a polyfill.

Categories : Javascript

Finding inner matches using Regular Expressions in Javascript
You can use this: var regex = /loanId=([^&"'s]+)/; var match = regex.exec(yourString); console.log(match[1]); the result is in the first capturing group. Since javascript regex doesn't have the lookbehind feature, this is the only way.

Categories : Javascript

Finding the root of a javascript function on a website
I suggest to use Firefox Firebug. Open Console and just type "poster". It will output function signature. You can hover on it to find out file or click on it to navigate to Script of Firebug. Check out screenshots. https://blog.gaurangjadia.com/?attachment_id=835 https://blog.gaurangjadia.com/?attachment_id=836 Also, you can put breakpoints and debug your scripts. It is nice and powerful web development tool. Example is at http://code.gaurangjadia.com/stackoverflow/18551051/

Categories : Javascript

Event object in Javascript, trouble finding information
Official W3c reccomendation clientX and clientY are the official event property handlers you are looking for. Although you might want to consider screenX and screenY too. Events (API) Events Creating, triggering events Event handlers Orientation and motion data Window Event X and Y property Explanation event.x and event.y, what are those? First of all, the x and y properties are not in all events. It is relative on the event triggered. Here is an example: document.body.onclick = function(){console.log(window.event.x)}; If you paste and execute that code in your browser's console, it will log you the x position of the cursor each time you click. Although taking a look at this example: document.body.onkeyup = function(){console.log(window.event.x)}; The console will

Categories : Javascript

Javascript - Regex finding multiple parentheses matches
Your regex has anchors to match beginning and end of the string, so it won't suffice to match multiple occurrences. Updated code using String.match with the RegExp g flag (global modifier): var userIn = 'Cu(NO3)2(CO2)3'; var inPar = userIn.match(/([^)]*)/g).map(function(s){ return s.substr(1); }); inPar; //["NO3)", "CO2)"] In case you need old IE support: Array.prototype.map polyfill Or without polyfills: var userIn = 'Cu(NO3)2(CO2)3'; var inPar = []; userIn.replace(/(([^)]*))/g, function(s, m) { inPar.push(m); }); inPar; //["NO3)", "CO2)"] Above matches a ( and captures a sequence of zero or more non-) characters, followed by a ) and pushes it to the inPar array. The first regex does essentially the same, but uses the entire match including the opening ( parenthesis (which is late

Categories : Javascript

Regex for finding Java's format strings in JavaScript
The problem lies in this group: (.[0-9]*) You expect a % at first then the . in the above group is expecting one of something (not optional). Then (d|i|u|f|F|e|E|g|G|x|X|o|s|S|c|C|a|A|b|B|h|H|p|n|%) is also expecting something. So basically the only required items in your regex are: 1. % 2. the . in (.[0-9]*) 3. (d|i|u|f|F|e|E|g|G|x|X|o|s|S|c|C|a|A|b|B|h|H|p|n|%) There isn't room in %s to accommodate the % and both the . and the chunk you are wanting to pull the s. I'm not sure exactly what you want (.[0-9]*) to be, but making it optional like (.[0-9]*)? would atleast allow for %s to pass.

Categories : Java

Google Maps - Finding all the markers inside a given radius Javascript/Php
Here is an example of how you could solve this with the geocoding API and some simple geometry. (Note that I have hardcoded the address and radius for brevity.) // we assume that you have an array of markers var markers = []; //In order to lookup the the position of a zip-code you can use the geocoding API: // https://developers.google.com/maps/documentation/geocoding/ var geocode_api_base_url = "http://maps.googleapis.com/maps/api/geocode/json?"; var params = { adress : 05673, components : "country:us", sensor : false } // This is the result set of markers in area var in_area = []; // http://maps.googleapis.com/maps/api/geocode/json?address=05673&components=country:US&sensor=false $.getJSON( geocode_api_base_url + $.param(params), function(data) { var loca

Categories : PHP

Regular expression for finding JavaScript arrays in html document
A pattern like this should work: ^var w+ = new Array(.*);$ This will match the beginning of the string (or line in multi-line mode), followed a literal var, followed by one or more 'word' characters followed by a literal = new Array( followed by zero or more of any characters, followed by a literal ); and the end of the string (or line in multi-line mode).

Categories : C

Summation of nth prime
OK, so I'm going to have a shot at this without saying too much because it looks like it might be a homework problem. My best guess is that a lot of people have shied away from even looking at your code because it's a bit too messy for their level of patience. It's not irredeemable, but you would probably get a better response if it were considerably cleaner. So, first, a few critical comments on your code to help you clean it up: it is insufficiently well-commented to make your intentions clear at any level, including what the overall purpose of the program is; it is inconsistently indented and spaced in an unconventional manner; and your choice of variable names leaves something to be desired, which is exacerbated by the absence of comments on variable declarations. You should compile

Categories : C

Prime factorization - list
You can use sieve Of Eratosthenes to generate all the primes up to (n/2) + 1 and then use a list comprehension to get all the prime factors: def rwh_primes2(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n%6>1) n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] sieve = [True] * (n/3) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1) sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1) return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]] def primeFac

Categories : Python

Loops and Prime Numbers
Use this method to check if a given int is a prime. public static boolean isPrime(int a) { if ( a == 2) return true; int midpoint = Math.round(a/2); for(int i = 2; i < midpoint; i++) { if(a % i == 0) return false; } return true; } Explanation: Loop through all the numbers until midpoint and modulus until you encounter 0 or not. If you encounter 0 then return false because we know that it is not prime, if we encounter no zero then we return true because it is prime. We loop until midpoint because there is no need to loop further. You can implement it in your loop via for (int i = 2; i < n ; i++) { if (isPrime(i)) { System.out.println(i); } }

Categories : Java

I need Prime font for my web site
final result: <style type="text/css"> @font-face { font-family: 'primelight'; src: url('prime_light-webfont.eot'); src: url('prime_light-webfont.eot?#iefix') format('embedded-opentype'), url('prime_light-webfont.woff') format('woff'), url('prime_light-webfont.ttf') format('truetype'), url('prime_light-webfont.svg#primelight') format('svg'); font-weight: normal; font-style: normal; } body { font-family: "primelight", Verdana, Tahoma; } </style> go to http://fontfabric.com/prime-free-font/ and download the font creat a repository in your website : fonts/prime/ put the prime files inside make sure you ve something like this :PrimeLight.otf alternative : download the font convert it with all op

Categories : CSS

How to count co-prime to n in a range [1,x] where x can be different from n?
You can use Inclusion-Exclusion Principle Find the unique prime factors of N (they cannot be more than 10-12, Considering N and X <=10^10). Now you can find the number of numbers <=x and divisible by 'y' just by dividing. Try all combination of factors of n for y (you will get only 2^10 (1024) in worst case). Use Inclusion Exclusion now to find the co-primes of n less than x. The idea is that if a number is not co-prime to n, then it will have at least one prime factor common with n. For our example here lets consider X=35 and N=30 First find the unique prime factor of the number. (their number must not be greater than 10-12). Unique Prime factor of N ={2,3,5}. Find the product of each factor PAIR. {2x3, 2x5, 3x5 or 6, 10, 15}. Find the product of each factor TRIPLET: {

Categories : C++

Not getting value on selection of row using prime faces
You need to set the rowKey attribute on the <p:dataTable/> to properly enable row selection. The rowKey attribute should be set to a unique identifier for the entity in your datatable, like the primary key attribute. From your sample, it'll look something like: <p:dataTable value="#{userManagedBean.dataModel}" rowKey="#{user.userId}" var="user" pagination="true" rows="5" selection="#{userManagedBean.selectedUser}" selectionMode="single">

Categories : JSF

Why does this prime test work?
Let's start with the first four lines of the function's code: def isprime(n): if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False The function tests to see if n is equal to 2 or 3 first. Since they are both prime numbers, the function will return True if n is equal to either. Next, the function tests to see if n is divisible by 2 or 3 and returning False if either is true. This eliminates an extremely large amount of cases because half of all numbers above two are not primes - they are divisible by 2. The same reason applies to testing for divisibility by 3 - it also eliminates a large number of cases. The trickier part of the function is in the next few lines: i = 5 w = 2 while i * i <= n: if n % i == 0:

Categories : Python

Prime number C++ program
i can never be equal to a - 1 - you're only going up to b - 1. b being a/2, that's never going to cause a match. That means your loop ending condition that would return 1 is never true. In the case of a prime number, you run off the end of the loop. That causes undefined behaviour, since you don't have a return statement there. Clang gave a warning, without any special flags: example.cpp:22:1: warning: control may reach end of non-void function [-Wreturn-type] } ^ 1 warning generated. If your compiler didn't warn you, you need to turn on some more warning flags. For example, adding -Wall gives a warning when using GCC: example.cpp: In function ‘bool primetest(int)’: example.cpp:22: warning: control reaches end of non-void function Overall, your prime-checking loop is

Categories : C++

Why does my prime generator break down?
You need to set divided_pass back to 0 for every new i. def find_primes(limit): prime_holder = [2, 3, 5 ,7] for i in range(11, 20000): divided_pass = 0 for j in range(0, len(prime_holder)): if i%prime_holder[j] != 0: divided_pass += 1 if divided_pass == len(prime_holder): prime_holder.append(i) if len(prime_holder)-1 == limit: break return prime_holder >>> print find_primes(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233] P.S - Lists are iterable in Python, so you don't need to do for j in range(len(...)

Categories : Python

Can someone explain this prime list generator for me?
looks like it's just array notation you're looking for. [a] * 5 just becomes [a,a,a,a,a] if sieve[i/2] is checking if the value of sieve at i/2 is True or False and the :: defines the stride. see this answer.

Categories : Python

Checking for prime number - C# logic
1 is a factor of every number, so you shouldn't check it. Start at 2. Also, you're already looping from 2 to sqrt(num), so there's no way for i to be equal to num.

Categories : C#

Prime Number Simple Test
Couple of problems in your original code: You are doing only one iteration You declare the array holding divisions inside the loop, causing it to always have maximum 1 item. Quick fix of the above would be: var primetest = function(n){ var divisor = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; var arr2 = []; for (var i = 0; i < divisor.length; i++) { if(n%divisor[i] == 0) { arr2.push(i); } } return arr2.length <=1; } Live test case. Optimized code that does not iterate through the whole list of divisors if not reuired (guess that's what you were trying to achieve) is: var primetest = function(n){ var divisor = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; var arr2 = []; for (var i = 0; i < divi

Categories : Javascript

Java API for Prime Number and Factorization
I suggest Commons Math. You can find lib here API here. The class that would be interesting for you is Primes.

Categories : Java

Prime Numbers in Java - Algorithms
What you can do is find the lowest divisor of Tn. Suppose that is p, find the lowest divisor again for Tn/p and so on. Now, at every step p is prime[explanation below]. So collect them and they are the prime divisors of Tn. For better time-complexity, you can check for divisors up to upto ceil(sqrt(Tn)) only, instead of Tn-1. And when you start checking for prime divisor for Tn, you can start with 2. And once you get a prime divisor p don't start again from 2 for Tn/p. Because, Tn/p is also a divisor of Tn and since Tn does not have divisors less than p, Tn/p does not have it too. So start with p again[p can have multiple power in Tn]. If p does not divide Tn, move to p+1. Example : Tn = 45 1. start with 2. 2 does not divides 45. 2. next test is for 3. 45 is divisible by 3. So 3 is a

Categories : Java

Python sieve prime numbers
for n in xrange(i,limit,i): a[n]=False It should be: for n in xrange(2*i,limit,i): a[n]=False Or, more efficiently: for n in xrange(i*i,limit, 2*i): #assuming you already cleared even numbers a[n]=False Because otherwise you end up setting i as non-prime, when it actually is a prime. (The sieve should mark all multiples of i as non-primes, except i itself!) Note that you are iterating over all the numbers, up to limit, but you can safely stopped after reaching sqrt(limit): import itertools as it def primesieve(limit): a = [True] * limit a[0] = a[1] = False sqrt_limit = int(limit**0.5) + 1 predicate = lambda x: x[0] <= sqrt_limit for i, isprime in it.takewhile(predicate, enumerate(a)): if isprime: for n in xrange(i*i, limit

Categories : Python

find Prime numbers up to X - complexity
If you are using the following code, the time complexity is O(x √x). int[] p = new int[x]; for (int i = 0; i < p.length; i++) { p[i] = i+1; } for (int i = 4; i <= p.length; i++) { for(int j = 2; j <= Math.sqrt(i) ; j += 1) { if(i%j==0) { p[i-1] = 0; } } }

Categories : Java

Determining Prime Numbers Java
Your problem lies with this line: if (isPrime = true){ You made an assignment, instead of comparing to true, so the statement is always true. Use == to compare boolean values, or better yet, since isPrime is already a boolean: if (isPrime){

Categories : Java

Compile time prime checking
You can take a look at constexpr. It has a lot friendlier syntax than template meta programming ( at least if you're unfamiliar with templates like me. ) You can't use if's, or any loops. But with recursion and the tenary opeartor you can do pretty much everything you can with template meta programming, and it usually runs faster too. http://cpptruths.blogspot.no/2011/07/want-speed-use-constexpr-meta.html Here's a working example using an online compiler : http://coliru.stacked-crooked.com/view?id=6bc10e71b8606dd2980c0c5dd982a3c0-6fbdb8a7476ab90c2bd2503cd4005881 Since it is executed at compile time, you can do a static assert to test it. static_assert(is_prime_func(x), "..."); The assert will fail if x is not a prime, meaning compilation will fail. If x is a prime, the compilation

Categories : C++

Prime Faces error Cannot add the same component twice
I solved this issue by setting the transient option=true. Because I was creating menus dynamically which resulted in "WARNING: Unable to save dynamic action with clientId 'j_idt8:j_idt9:0:j_id3' because the UIComponent cannot be found" and "Cannot remove the same component twice: j_idt8:j_idt9:j_id3" problems. public void setMenus(String type) { MenuItem item; item=new MenuItem(); item.setValue("Change Password"); item.setStyle("color:black"); item.setTransient(true); /* Set this to solve the problem */ item.setUrl("/adminAccount/changepassword.xhtml"); submenus.addMenuItem(item); }

Categories : JSF

Setting a counter using prime faces
You don't want to have a separate table - do you mean a table in the database? (very vague formulated question, but I think I know what you mean). If so, add a numeric field of your choise to your Locality entity: @Entity public class Locality { private String name; private int counter; public voidincreaseCounter() { counter++; } public int getCounter() { return this.counter; } } ... and when the search has happened increase the counter from that locality: public void searchPerformed(String searchString) { String locality = ....// parse the search string Locality locality = localityRepository.getLocality(localityName); if (locality == null) { locality = new Locality(localityName); } locality.increaseCounter(); System.out.println("New counter for " +

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.