Search Results

Search found 425 results on 17 pages for 'prime'.

Page 3/17 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Is bundler ready for prime time?

    - by schof
    I'm considering using bundler for deploying a Spree app on Heroku. My question is, is bundler ready for prime time? I know there are some rough edges but I guess I'd like to know more about what the current limitations are and figure out if this is an option for us. Specifically, I'd like to do the git repository stuff git "git://github.com/indirect/rails3-generators.git" gem "rails3-generator Does anyone want to encourage/discourage me from this course of action? Anybody have experience with this on Heroku in particular?

    Read the article

  • Prime Number - Data while loading

    - by Emroot
    Hi, I was trying in Ruby on Rails how to find a prime number. Here is my code : helper : app/helpers/test_helper.rb module TestHelper def prime_number? number index = 2 tmp = 0 while index <= number if tmp < 1 if (number % index) == 0 tmp += 1 end else return false end index += 1 end return true end end and my view : app/views/test/index.html.erb <% (2..100).each do |i| -%> <% if prime_number? i %> <%= i %> <% end -%> <% end -%> So my question is : How can you load data while it's calculating ? I mean if I replace 100 by 100000 in my view, how can I see data on my view while my helper method is calculating ? Do I need to use ajax or rails provide a tool for that ? Thank you.

    Read the article

  • Enumerating large (20-digit) [probable] prime numbers

    - by Paul Baker
    Given A, on the order of 10^20, I'd like to quickly obtain a list of the first few prime numbers greater than A. OK, my needs aren't quite that exact - it's alright if occasionally a composite number ends up on the list. What's the fastest way to enumerate the (probable) primes greater than A? Is there a quicker way than stepping through all of the integers greater than A (other than obvious multiples of say, 2 and 3) and performing a primality test for each of them? If not, and the only method is to test each integer, what primality test should I be using?

    Read the article

  • Simple prime number program - Weird issue with threads C#

    - by Para
    Hi! This is my code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace FirePrime { class Program { static bool[] ThreadsFinished; static bool[] nums; static bool AllThreadsFinished() { bool allThreadsFinished = false; foreach (var threadFinished in ThreadsFinished) { allThreadsFinished &= threadFinished; } return allThreadsFinished; } static bool isPrime(int n) { if (n < 2) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } int d = 3; while (d * d <= n) { if (n % d == 0) { return false; } d += 2; } return true; } static void MarkPrimes(int startNumber,int stopNumber,int ThreadNr) { for (int j = startNumber; j < stopNumber; j++) nums[j] = isPrime(j); lock (typeof(Program)) { ThreadsFinished[ThreadNr] = true; } } static void Main(string[] args) { int nrNums = 100; int nrThreads = 10; //var threadStartNums = new List<int>(); ThreadsFinished = new bool[nrThreads]; nums = new bool[nrNums]; //var nums = new List<bool>(); nums[0] = false; nums[1] = false; for(int i=2;i<nrNums;i++) nums[i] = true; int interval = (int)(nrNums / nrThreads); //threadStartNums.Add(2); //int aux = firstStartNum; //int i = 2; //while (aux < interval) //{ // aux = interval*i; // i=i+1; // threadStartNums.Add(aux); //} int startNum = 0; for (int i = 0; i < nrThreads; i++) { var _thread = new System.Threading.Thread(() => MarkPrimes(startNum, Math.Min(startNum + interval, nrNums), i)); startNum = startNum + interval; //set the thread to run in the background _thread.IsBackground = true; //start our thread _thread.Start(); } while (!AllThreadsFinished()) { Thread.Sleep(1); } for (int i = 0; i < nrNums; i++) if(nums[i]) Console.WriteLine(i); } } } This should be a pretty simple program that is supposed to find and output the first nrNums prime numbers using nrThreads threads working in parallel. So, I just split nrNums into nrThreads equal chunks (well, the last one won't be equal; if nrThreads doesn't divide by nrNums, it will also contain the remainder, of course). I start nrThreads threads. They all test each number in their respective chunk and see if it is prime or not; they mark everything out in a bool array that keeps a tab on all the primes. The threads all turn a specific element in another boolean array ThreadsFinished to true when they finish. Now the weird part begins: The threads never all end. If I debug, I find that ThreadNr is not what I assign to it in the loop but another value. I guess this is normal since the threads execute afterwards and the counter (the variable i) is already increased by then but I cannot understand how to make the code be right. Can anyone help? Thank you in advance. P.S.: I know the algorithm is not very efficient; I am aiming at a solution using the sieve of Eratosthenes also with x given threads. But for now I can't even get this one to work and I haven't found any examples of any implementations of that algorithm anywhere in a language that I can understand.

    Read the article

  • Trying to calculate the 10001st prime number in Java.

    - by user247679
    Greetings. I am doing Problem 7 from Project Euler. What I am supposed to do is calculate the 10001st prime number. (A prime number being a number that is only divisible by itself and one.) Here is my current program: public class Problem7 { public static void main(String args []){ long numberOfPrimes = 0; long number = 2; while (numberOfPrimes < 10001){ if(isPrime(number)){ numberOfPrimes++; } number++; } System.out.println("10001st prime: "+ number); } public static boolean isPrime(long N) { if (N <= 1) return false; else return Prime(N,N-1); } public static boolean Prime(long X,long Y) { if (Y == 1) return true; else if (X % Y == 0) return false; else return Prime(X, Y-1); } } It works okay with finding, say the 100th prime number, but when I enter very large numbers such as 10001 it causes a stack overflow. Does anyone know of a way to fix this? Thanks for reading my problem!

    Read the article

  • C#, finding the largest prime factor of a number

    - by Juan
    Hello! I am new at programming and I am practicing my C# programming skills. My application is meant to find the largest prime factor of a number entered by the user. But my application is not returning the right answer and I dont really know where the problem is. Can you please help me? using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Calcular máximo factor primo de n. De 60 es 5."); Console.Write("Escriba un numero: "); long num = Convert.ToInt64(Console.ReadLine()); long mfp = maxfactor(num); Console.WriteLine("El maximo factor primo es: " + num); Console.Read(); } static private long maxfactor (long n) { long m=1 ; bool en= false; for (long k = n / 2; !en && k > 1; k--) { if (n % k == 0 && primo(k)) { m = k; en = true; } } return m; } static private bool primo(long x) { bool sp = true; for (long i = 2; i <= x / 2; i++) { if (x % i == 0) sp = false; } return sp; } } }

    Read the article

  • Go and a bad prime number algorithm

    - by anonymous
    I wrote this prime number sieving algorithm and it doesn't run properly. I can't find the error in the algorithm itself. Could someone help me? This is what it's supposed to print: [2 3 5 7 11 13 17 19 23 29] Versus what it actually prints: [3 5 7 11 13 17 19 23 25 29] . package main import "fmt" func main() { var primes = sieve(makeNumbers(29)) fmt.Printf("%d\n", primes); } func makeNumbers(n int) []int { var numbers = make([]int, n - 1) for i := 0; i < len(numbers); i++ { numbers[i] = i + 2 } return numbers } func sieve(numbers []int) []int { var numCopy = numbers var max = numbers[len(numbers)-1] var sievedNumbers = make([]int, 0) for i := 0; numCopy[i]*numCopy[i] <= max; i++ { for j := i; j < len(numCopy); j++ { if numCopy[j] % numCopy[i] != 0 || j == i { sievedNumbers = append(sievedNumbers, numCopy[j]) } } numCopy = sievedNumbers sievedNumbers = make([]int, 0) } return numCopy }

    Read the article

  • ANTS CLR and Memory Profiler In Depth Review (Part 1 of 2 &ndash; CLR Profiler)

    - by ToStringTheory
    One of the things that people might not know about me, is my obsession to make my code as efficient as possible.  Many people might not realize how much of a task or undertaking that this might be, but it is surely a task as monumental as climbing Mount Everest, except this time it is a challenge for the mind…  In trying to make code efficient, there are many different factors that play a part – size of project or solution, tiers, language used, experience and training of the programmer, technologies used, maintainability of the code – the list can go on for quite some time. I spend quite a bit of time when developing trying to determine what is the best way to implement a feature to accomplish the efficiency that I look to achieve.  One program that I have recently come to learn about – Red Gate ANTS Performance (CLR) and Memory profiler gives me tools to accomplish that job more efficiently as well.  In this review, I am going to cover some of the features of the ANTS profiler set by compiling some hideous example code to test against. Notice As a member of the Geeks With Blogs Influencers program, one of the perks is the ability to review products, in exchange for a free license to the program.  I have not let this affect my opinions of the product in any way, and Red Gate nor Geeks With Blogs has tried to influence my opinion regarding this product in any way. Introduction The ANTS Profiler pack provided by Red Gate was something that I had not heard of before receiving an email regarding an offer to review it for a license.  Since I look to make my code efficient, it was a no brainer for me to try it out!  One thing that I have to say took me by surprise is that upon downloading the program and installing it you fill out a form for your usual contact information.  Sure enough within 2 hours, I received an email from a sales representative at Red Gate asking if she could help me to achieve the most out of my trial time so it wouldn’t go to waste.  After replying to her and explaining that I was looking to review its feature set, she put me in contact with someone that setup a demo session to give me a quick rundown of its features via an online meeting.  After having dealt with a massive ordeal with one of my utility companies and their complete lack of customer service, Red Gates friendly and helpful representatives were a breath of fresh air, and something I was thankful for. ANTS CLR Profiler The ANTS CLR profiler is the thing I want to focus on the most in this post, so I am going to dive right in now. Install was simple and took no time at all.  It installed both the profiler for the CLR and Memory, but also visual studio extensions to facilitate the usage of the profilers (click any images for full size images): The Visual Studio menu options (under ANTS menu) Starting the CLR Performance Profiler from the start menu yields this window If you follow the instructions after launching the program from the start menu (Click File > New Profiling Session to start a new project), you are given a dialog with plenty of options for profiling: The New Session dialog.  Lots of options.  One thing I noticed is that the buttons in the lower right were half-covered by the panel of the application.  If I had to guess, I would imagine that this is caused by my DPI settings being set to 125%.  This is a problem I have seen in other applications as well that don’t scale well to different dpi scales. The profiler options give you the ability to profile: .NET Executable ASP.NET web application (hosted in IIS) ASP.NET web application (hosted in IIS express) ASP.NET web application (hosted in Cassini Web Development Server) SharePoint web application (hosted in IIS) Silverlight 4+ application Windows Service COM+ server XBAP (local XAML browser application) Attach to an already running .NET 4 process Choosing each option provides a varying set of other variables/options that one can set including options such as application arguments, operating path, record I/O performance performance counters to record (43 counters in all!), etc…  All in all, they give you the ability to profile many different .Net project types, and make it simple to do so.  In most cases of my using this application, I would be using the built in Visual Studio extensions, as they automatically start a new profiling project in ANTS with the options setup, and start your program, however RedGate has made it easy enough to profile outside of Visual Studio as well. On the flip side of this, as someone who lives most of their work life in Visual Studio, one thing I do wish is that instead of opening an entirely separate application/gui to perform profiling after launching, that instead they would provide a Visual Studio panel with the information, and integrate more of the profiling project information into Visual Studio.  So, now that we have an idea of what options that the profiler gives us, its time to test its abilities and features. Horrendous Example Code – Prime Number Generator One of my interests besides development, is Physics and Math – what I went to college for.  I have especially always been interested in prime numbers, as they are something of a mystery…  So, I decided that I would go ahead and to test the abilities of the profiler, I would write a small program, website, and library to generate prime numbers in the quantity that you ask for.  I am going to start off with some terrible code, and show how I would see the profiler being used as a development tool. First off, the IPrimes interface (all code is downloadable at the end of the post): interface IPrimes { IEnumerable<int> GetPrimes(int retrieve); } Simple enough, right?  Anything that implements the interface will (hopefully) provide an IEnumerable of int, with the quantity specified in the parameter argument.  Next, I am going to implement this interface in the most basic way: public class DumbPrimes : IPrimes { public IEnumerable<int> GetPrimes(int retrieve) { //store a list of primes already found var _foundPrimes = new List<int>() { 2, 3 }; //if i ask for 1 or two primes, return what asked for if (retrieve <= _foundPrimes.Count()) return _foundPrimes.Take(retrieve); //the next number to look at int _analyzing = 4; //since I already determined I don't have enough //execute at least once, and until quantity is sufficed do { //assume prime until otherwise determined bool isPrime = true; //start dividing at 2 //divide until number is reached, or determined not prime for (int i = 2; i < _analyzing && isPrime; i++) { //if (i) goes into _analyzing without a remainder, //_analyzing is NOT prime if (_analyzing % i == 0) isPrime = false; } //if it is prime, add to found list if (isPrime) _foundPrimes.Add(_analyzing); //increment number to analyze next _analyzing++; } while (_foundPrimes.Count() < retrieve); return _foundPrimes; } } This is the simplest way to get primes in my opinion.  Checking each number by the straight definition of a prime – is it divisible by anything besides 1 and itself. I have included this code in a base class library for my solution, as I am going to use it to demonstrate a couple of features of ANTS.  This class library is consumed by a simple non-MVVM WPF application, and a simple MVC4 website.  I will not post the WPF code here inline, as it is simply an ObservableCollection<int>, a label, two textbox’s, and a button. Starting a new Profiling Session So, in Visual Studio, I have just completed my first stint developing the GUI and DumbPrimes IPrimes class, so now I want to check my codes efficiency by profiling it.  All I have to do is build the solution (surprised initiating a profiling session doesn’t do this, but I suppose I can understand it), and then click the ANTS menu, followed by Profile Performance.  I am then greeted by the profiler starting up and already monitoring my program live: You are provided with a realtime graph at the top, and a pane at the bottom giving you information on how to proceed.  I am going to start by asking my program to show me the first 15000 primes: After the program finally began responding again (I did all the work on the main UI thread – how bad!), I stopped the profiler, which did kill the process of my program too.  One important thing to note, is that the profiler by default wants to give you a lot of detail about the operation – line hit counts, time per line, percent time per line, etc…  The important thing to remember is that this itself takes a lot of time.  When running my program without the profiler attached, it can generate the 15000 primes in 5.18 seconds, compared to 74.5 seconds – almost a 1500 percent increase.  While this may seem like a lot, remember that there is a trade off.  It may be WAY more inefficient, however, I am able to drill down and make improvements to specific problem areas, and then decrease execution time all around. Analyzing the Profiling Session After clicking ‘Stop Profiling’, the process running my application stopped, and the entire execution time was automatically selected by ANTS, and the results shown below: Now there are a number of interesting things going on here, I am going to cover each in a section of its own: Real Time Performance Counter Bar (top of screen) At the top of the screen, is the real time performance bar.  As your application is running, this will constantly update with the currently selected performance counters status.  A couple of cool things to note are the fact that you can drag a selection around specific time periods to drill down the detail views in the lower 2 panels to information pertaining to only that period. After selecting a time period, you can bookmark a section and name it, so that it is easy to find later, or after reloaded at a later time.  You can also zoom in, out, or fit the graph to the space provided – useful for drilling down. It may be hard to see, but at the top of the processor time graph below the time ticks, but above the red usage graph, there is a green bar. This bar shows at what times a method that is selected in the ‘Call tree’ panel is called. Very cool to be able to click on a method and see at what times it made an impact. As I said before, ANTS provides 43 different performance counters you can hook into.  Click the arrow next to the Performance tab at the top will allow you to change between different counters if you have them selected: Method Call Tree, ADO.Net Database Calls, File IO – Detail Panel Red Gate really hit the mark here I think. When you select a section of the run with the graph, the call tree populates to fill a hierarchical tree of method calls, with information regarding each of the methods.   By default, methods are hidden where the source is not provided (framework type code), however, Red Gate has integrated Reflector into ANTS, so even if you don’t have source for something, you can select a method and get the source if you want.  Methods are also hidden where the impact is seen as insignificant – methods that are only executed for 1% of the time of the overall calling methods time; in other words, working on making them better is not where your efforts should be focused. – Smart! Source Panel – Detail Panel The source panel is where you can see line level information on your code, showing the code for the currently selected method from the Method Call Tree.  If the code is not available, Reflector takes care of it and shows the code anyways! As you can notice, there does seem to be a problem with how ANTS determines what line is the actual line that a call is completed on.  I have suspicions that this may be due to some of the inline code optimizations that the CLR applies upon compilation of the assembly.  In a method with comments, the problem is much more severe: As you can see here, apparently the most offending code in my base library was a comment – *gasp*!  Removing the comments does help quite a bit, however I hope that Red Gate works on their counter algorithm soon to improve the logic on positioning for statistics: I did a small test just to demonstrate the lines are correct without comments. For me, it isn’t a deal breaker, as I can usually determine the correct placements by looking at the application code in the region and determining what makes sense, but it is something that would probably build up some irritation with time. Feature – Suggest Method for Optimization A neat feature to really help those in need of a pointer, is the menu option under tools to automatically suggest methods to optimize/improve: Nice feature – clicking it filters the call tree and stars methods that it thinks are good candidates for optimization.  I do wish that they would have made it more visible for those of use who aren’t great on sight: Process Integration I do think that this could have a place in my process.  After experimenting with the profiler, I do think it would be a great benefit to do some development, testing, and then after all the bugs are worked out, use the profiler to check on things to make sure nothing seems like it is hogging more than its fair share.  For example, with this program, I would have developed it, ran it, tested it – it works, but slowly. After looking at the profiler, and seeing the massive amount of time spent in 1 method, I might go ahead and try to re-implement IPrimes (I actually would probably rewrite the offending code, but so that I can distribute both sets of code easily, I’m just going to make another implementation of IPrimes).  Using two pieces of knowledge about prime numbers can make this method MUCH more efficient – prime numbers fall into two buckets 6k+/-1 , and a number is prime if it is not divisible by any other primes before it: public class SmartPrimes : IPrimes { public IEnumerable<int> GetPrimes(int retrieve) { //store a list of primes already found var _foundPrimes = new List<int>() { 2, 3 }; //if i ask for 1 or two primes, return what asked for if (retrieve <= _foundPrimes.Count()) return _foundPrimes.Take(retrieve); //the next number to look at int _k = 1; //since I already determined I don't have enough //execute at least once, and until quantity is sufficed do { //assume prime until otherwise determined bool isPrime = true; int potentialPrime; //analyze 6k-1 //assign the value to potential potentialPrime = 6 * _k - 1; //if there are any primes that divise this, it is NOT a prime number //using PLINQ for quick boost isPrime = !_foundPrimes.AsParallel() .Any(prime => potentialPrime % prime == 0); //if it is prime, add to found list if (isPrime) _foundPrimes.Add(potentialPrime); if (_foundPrimes.Count() == retrieve) break; //analyze 6k+1 //assign the value to potential potentialPrime = 6 * _k + 1; //if there are any primes that divise this, it is NOT a prime number //using PLINQ for quick boost isPrime = !_foundPrimes.AsParallel() .Any(prime => potentialPrime % prime == 0); //if it is prime, add to found list if (isPrime) _foundPrimes.Add(potentialPrime); //increment k to analyze next _k++; } while (_foundPrimes.Count() < retrieve); return _foundPrimes; } } Now there are definitely more things I can do to help make this more efficient, but for the scope of this example, I think this is fine (but still hideous)! Profiling this now yields a happy surprise 27 seconds to generate the 15000 primes with the profiler attached, and only 1.43 seconds without.  One important thing I wanted to call out though was the performance graph now: Notice anything odd?  The %Processor time is above 100%.  This is because there is now more than 1 core in the operation.  A better label for the chart in my mind would have been %Core time, but to each their own. Another odd thing I noticed was that the profiler seemed to be spot on this time in my DumbPrimes class with line details in source, even with comments..  Odd. Profiling Web Applications The last thing that I wanted to cover, that means a lot to me as a web developer, is the great amount of work that Red Gate put into the profiler when profiling web applications.  In my solution, I have a simple MVC4 application setup with 1 page, a single input form, that will output prime values as my WPF app did.  Launching the profiler from Visual Studio as before, nothing is really different in the profiler window, however I did receive a UAC prompt for a Red Gate helper app to integrate with the web server without notification. After requesting 500, 1000, 2000, and 5000 primes, and looking at the profiler session, things are slightly different from before: As you can see, there are 4 spikes of activity in the processor time graph, but there is also something new in the call tree: That’s right – ANTS will actually group method calls by get/post operations, so it is easier to find out what action/page is giving the largest problems…  Pretty cool in my mind! Overview Overall, I think that Red Gate ANTS CLR Profiler has a lot to offer, however I think it also has a long ways to go.  3 Biggest Pros: Ability to easily drill down from time graph, to method calls, to source code Wide variety of counters to choose from when profiling your application Excellent integration/grouping of methods being called from web applications by request – BRILLIANT! 3 Biggest Cons: Issue regarding line details in source view Nit pick – Processor time vs. Core time Nit pick – Lack of full integration with Visual Studio Ratings Ease of Use (7/10) – I marked down here because of the problems with the line level details and the extra work that that entails, and the lack of better integration with Visual Studio. Effectiveness (10/10) – I believe that the profiler does EXACTLY what it purports to do.  Especially with its large variety of performance counters, a definite plus! Features (9/10) – Besides the real time performance monitoring, and the drill downs that I’ve shown here, ANTS also has great integration with ADO.Net, with the ability to show database queries run by your application in the profiler.  This, with the line level details, the web request grouping, reflector integration, and various options to customize your profiling session I think create a great set of features! Customer Service (10/10) – My entire experience with Red Gate personnel has been nothing but good.  their people are friendly, helpful, and happy! UI / UX (8/10) – The interface is very easy to get around, and all of the options are easy to find.  With a little bit of poking around, you’ll be optimizing Hello World in no time flat! Overall (8/10) – Overall, I am happy with the Performance Profiler and its features, as well as with the service I received when working with the Red Gate personnel.  I WOULD recommend you trying the application and seeing if it would fit into your process, BUT, remember there are still some kinks in it to hopefully be worked out. My next post will definitely be shorter (hopefully), but thank you for reading up to here, or skipping ahead!  Please, if you do try the product, drop me a message and let me know what you think!  I would love to hear any opinions you may have on the product. Code Feel free to download the code I used above – download via DropBox

    Read the article

  • Project Euler 7: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 7.  As always, any feedback is welcome. # Euler 7 # http://projecteuler.net/index.php?section=problems&id=7 # By listing the first six prime numbers: 2, 3, 5, 7, # 11, and 13, we can see that the 6th prime is 13. What # is the 10001st prime number? import time start = time.time() def nthPrime(nth): primes = [2] number = 3 while len(primes) < nth: isPrime = True for prime in primes: if number % prime == 0: isPrime = False break if (prime * prime > number): break if isPrime: primes.append(number) number += 2 return primes[nth - 1] print nthPrime(10001) print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • How to account for non-prime numbers 0 and 1 in java?

    - by shady
    I'm not sure if this is the right place to be asking this, but I've been searching for a solution for this on my own for quite some time, so hopefully I've come to the right place. When calculating prime numbers, the starting number that each number has to be divisible by is 2 to be a non-prime number. In my java program, I want to include all the non-prime numbers in the range from 0 to a certain number, so how do I include 0 and 1? Should I just have separate if and else-if statements for 0 and 1 that state that they are not prime numbers? I think that maybe 0 and 1 should be included in the java for loop, but I don't know how to go about doing that. for (int i = 2; i < num; i++){ if (num % i == 0){ System.out.println(i + " is not a prime number. "); } else{ System.out.println(i + " is a prime number. "); } }

    Read the article

  • Count the prime numbers from 2 to 100 with simpler code than this

    - by RufioLJ
    It has to be with just functions, variables, loops, etc (Basic stuff). I'm having trouble coming up with the code from scratch from what I've I learned so far(Should be able to do it). Makes me really mad :/. If you could give me step by step to make sure I understand I'd really really appreciated. Thanks a bunch in advanced. How could I get the same result with a simpler code than this one: var primes=4; for (var counter = 2; counter <= 100; counter = counter + 1) { var isPrime = 0; if(isPrime === 0){ if(counter === 2){console.log(counter);} else if(counter === 3){console.log(counter);} else if(counter === 5){console.log(counter);} else if(counter === 7){console.log(counter);} else if(counter % 2 === 0){isPrime=0;} else if(counter % 3 === 0){isPrime=0;} else if(counter % 5 === 0){isPrime=0;} else if(counter % 7 === 0){isPrime=0;} else { console.log(counter); primes = primes + 1; } } } console.log("Counted: "+primes+" primes");

    Read the article

  • mod,prime -> inverse possible

    - by Piet
    Hi all. I was wondering if one can do the following: We have: X is a product of N-primes, thus I assume unique. C is a constant. We can assure that C is a number that is part of the N-primes or not. Whichever will work best. Thus: X mod C = Z We have Z and C and we know that X was a product of N-primes, where N is restricted lets say first 100 primes. Is there anyway we can get back X?

    Read the article

  • sum of logarithams of prime numbers

    - by nadi
    Write a program that computes the sum of the logarithms of all the primes from 2 to some number n, and print out the sum of the logs of the primes, the number n, and the ratio of these two quantities. Test this for different values of n.

    Read the article

  • Explanation needed for sum of prime below n numbers

    - by Bala Krishnan
    Today I solved a problem given in Project Euler its problem no 10 and it took 7 hrs for my python program to show the result. But in that forum itself a person named lassevk posted solution for this and it took only 4 sec. And its not possible for me to post this question in that forum because its not discussion forum. So, think about this if you want to mark this question as non-constructive. marked = [0] * 2000000 value = 3 s = 2 while value < 2000000: if marked[value] == 0: s += value i = value while i < 2000000: marked[i] = 1 i += value value += 2 print s If any one understand this code please explain it simple as possible. Link to the Problem 10 question.

    Read the article

  • Optimizing list comprehension to find pairs of co-prime numbers

    - by user3685422
    Given A,B print the number of pairs (a,b) such that GCD(a,b)=1 and 1<=a<=A and 1<=b<=B. Here is my answer: return len([(x,y) for x in range(1,A+1) for y in range(1,B+1) if gcd(x,y) == 1]) My answer works fine for small ranges but takes enough time if the range is increased. such as 1 <= A <= 10^5 1 <= B <= 10^5 is there a better way to write this or can this be optimized?

    Read the article

  • Javascript: find first n prime numbers

    - by bard
    function primeNumbers() { array = []; for (var i = 2; array.length < 100; i++) { for (var count = 2; count < i; count++) { var divisorFound = false; if (i % count === 0) { divisorFound = true; break; } } if (divisorFound == false) {array.push[i];} } return array; } When I run this code, it seems to get stuck in an infinite loop and doesn't return anything... why?

    Read the article

  • get greatest prime factor in F#

    - by Alex
    I had VS 11 beta and the following code was working without problem: let rec fac x y = if (x = y) then y elif (x % y = 0I) then fac (x / y) y else fac x / (y + 1I);; Now I installed VS 2012 RC and I get the following error: The type 'System.Numerics.BigInteger -> System.Numerics.BigInteger' is not compatible with the type 'System.Numerics.BigInteger' Is code not correct or F# interactive? It's F# 3.0.

    Read the article

  • Finding the nth number of primes

    - by Braxton Smith
    I can not figure out why this won't work. Please help me from math import sqrt pN = 0 numPrimes = 0 num = 1 def checkPrime(x): '''Check\'s whether a number is a prime or not''' prime = True if(x==2): prime = True elif(x%2==0): prime=False else: root=int(sqrt(x)) for i in range(3,root,2): if(x%i==0): prime=False break return prime n = int(input("Find n number of primes. N being:")) while( numPrimes != n ): if( checkPrime( num ) == True ): numPrimes += 1 pN = num print("{0}: {1}".format(numPrimes,pN)) num += 1 print("Prime {0} is: {1}".format(n,pN))

    Read the article

  • "EXC_BAD_ACCESS: Unable to restore previously selected frame" Error, Array size?

    - by Job
    Hi there, I have an algorithm for creating the sieve of Eratosthenes and pulling primes from it. It lets you enter a max value for the sieve and the algorithm gives you the primes below that value and stores these in a c-style array. Problem: Everything works fine with values up to 500.000, however when I enter a large value -while running- it gives me the following error message in xcode: Program received signal: “EXC_BAD_ACCESS”. warning: Unable to restore previously selected frame. Data Formatters temporarily unavailable, will re-try after a 'continue'. (Not safe to call dlopen at this time.) My first idea was that I didn't use large enough variables, but as I am using 'unsigned long long int', this should not be the problem. Also the debugger points me to a point in my code where a point in the array get assigned a value. Therefore I wonder is there a maximum limit to an array? If yes: should I use NSArray instead? If no, then what is causing this error based on this information? EDIT: This is what the code looks like (it's not complete, for it fails at the last line posted). I'm using garbage collection. /*--------------------------SET UP--------------------------*/ unsigned long long int upperLimit = 550000; // unsigned long long int sieve[upperLimit]; unsigned long long int primes[upperLimit]; unsigned long long int indexCEX; unsigned long long int primesCounter = 0; // Fill sieve with 2 to upperLimit for(unsigned long long int indexA = 0; indexA < upperLimit-1; ++indexA) { sieve[indexA] = indexA+2; } unsigned long long int prime = 2; /*-------------------------CHECK & FIND----------------------------*/ while(!((prime*prime) > upperLimit)) { //check off all multiples of prime for(unsigned long long int indexB = prime-2; indexB < upperLimit-1; ++indexB) { // Multiple of prime = 0 if(sieve[indexB] != 0) { if(sieve[indexB] % prime == 0) { sieve[indexB] = 0; } } } /*---------------- Search for next prime ---------------*/ // index of current prime + 1 unsigned long long int indexC = prime - 1; while(sieve[indexC] == 0) { ++indexC; } prime = sieve[indexC]; // Store prime in primes[] primes[primesCounter] = prime; // This is where the code fails if upperLimit > 500000 ++primesCounter; indexCEX = indexC + 1; } As you may or may not see, is that I am -very much- a beginner. Any other suggestions are welcome of course :)

    Read the article

  • Why is my implementation of the Sieve of Atkin overlooking numbers close to the specified limit?

    - by Ross G
    My implementation either overlooks primes near the limit or composites near the limit. while some limits work and others don't. I'm am completely confused as to what is wrong. def AtkinSieve (limit): results = [2,3,5] sieve = [False]*limit factor = int(math.sqrt(lim)) for i in range(1,factor): for j in range(1, factor): n = 4*i**2+j**2 if (n <= lim) and (n % 12 == 1 or n % 12 == 5): sieve[n] = not sieve[n] n = 3*i**2+j**2 if (n <= lim) and (n % 12 == 7): sieve[n] = not sieve[n] if i>j: n = 3*i**2-j**2 if (n <= lim) and (n % 12 == 11): sieve[n] = not sieve[n] for index in range(5,factor): if sieve[index]: for jndex in range(index**2, limit, index**2): sieve[jndex] = False for index in range(7,limit): if sieve[index]: results.append(index) return results For example, when I generate a primes to the limit of 1000, the Atkin sieve misses the prime 997, but includes the composite 965. But if I generate up the limit of 5000, the list it returns is completely correct.

    Read the article

  • Why is my implementation of the Sieve of Atkin overlooking numbers close to the specified limit?

    - by Ross G
    My implementation either overlooks primes near the limit or composites near the limit. while some limits work and others don't. I'm am completely confused as to what is wrong. def AtkinSieve (limit): results = [2,3,5] sieve = [False]*limit factor = int(math.sqrt(lim)) for i in range(1,factor): for j in range(1, factor): n = 4*i**2+j**2 if (n <= lim) and (n % 12 == 1 or n % 12 == 5): sieve[n] = not sieve[n] n = 3*i**2+j**2 if (n <= lim) and (n % 12 == 7): sieve[n] = not sieve[n] if i>j: n = 3*i**2-j**2 if (n <= lim) and (n % 12 == 11): sieve[n] = not sieve[n] for index in range(5,factor): if sieve[index]: for jndex in range(index**2, limit, index**2): sieve[jndex] = False for index in range(7,limit): if sieve[index]: results.append(index) return results For example, when I generate a primes to the limit of 1000, the Atkin sieve misses the prime 997, but includes the composite 965. But if I generate up the limit of 5000, the list it returns is completely correct.

    Read the article

  • How do I EFI boot Zenbook Prime UX31A from built-in card reader?

    - by Richard Ayotte
    How do I EFI boot Zenbook Prime UX31A from built-in card reader? Ubuntu 12.10 64bit has been copied onto an a SD card which I'm trying to boot from. When I power on my Zenbook and press ESC, the SD card isn't an option. There is an "Add boot option" in the BIOS but it requires a few a things that I'm not quite sure of. Add boot option - I guess any identifier works here. I've been entering ubuntu. Select Filesystem - The only option available is PCI(1F|2)\DevicePath(Type 3, SubType 12)HD(Part1,Sig787e6287-xxxx-xxxx-xxxx-xxxxxxxxxxxx) Path for boot option - I've been entering ubuntu:\EFI\BOOT\BOOTx64.EFI Then I select Create and the new boot option appears in the boot menu but it doesn't work.

    Read the article

  • Can't find the error in my javascript code

    - by Olivier
    This js program should display the first 100 prime numbers, but instead it crashes each and every time and I can't find the error! Could someone point me towards the best way to debug js code?! Thank you! // initialisation of the array p holding the first 100 prime numbers var p = []; // set the first prime number to 2 p.push(2); // find the first 100 prime numbers and place them in the array p var i = 3; while (p.length < 100) { var prime = true; loop: for (var item in p){ if (i%item === 0){ prime = false; break loop; } } if (prime) p.push(i); i = i + 2; } // display the first 100 prime numbers found var i=1; for (var item in p){ document.writeln(i,item); i++; }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >