fertcleveland.blogg.se

Composite numbers
Composite numbers











Check the input array for non-prime numbersįor (int i = 0 i < inputNumbers. First, find all the prime numbers from 1 to n

#COMPOSITE NUMBERS CODE#

This code is to illustrate the algorithm only) vector inputNumbers

composite numbers

So a pseudo C code for your problem would be (I haven't run this through compilers yet, so please ignore syntax errors. That's very inefficient.Īs other guys suggested, you need to do something like the Sieve of Eratosthenes.

  • You keep on checking your numbers again and again.
  • You did not check if your number is dividing by itself.
  • If you want to test if your number is prime or non-prime, you would need to check for v % i = 0, not the other way round.
  • IMHO it'll be easier to understand than the way you've written it - testing each number for divisibility by k < n for ever increasing k. If you're going to test each number individually (using, I guess, and inverse sieve) then I suggest testing each number individually, in order. This may be quicker and easier to understand, especially if you store the primes somewhere. You could use a sieve to generate all primes up to n and then just remove those values from the input vector, as also suggested above. And you can figure out the max fairly quickly (but if you know it ahead of time you may as well pass it in).Īs mentioned above, you only need to test to sqrt(n) You don't need to pass in the number of elements in the vector - you just query the vector's size.

    composite numbers

    Using n as the maximum value in the vector and the number of elements in the vector is confusing and pointless. Second, your output will contain duplicates as you're testing and outputting each input number every time it fails the (broken) divisibility test. First, you're testing i % v = 0, which is backwards and also explains why you get all numbers. They are placed in this: vector nĪnd the values are inserted like this: srand(1) A composite number is a positive integer that has at least one divisor other than 1 and. The range is actually determined by the user but it will be up to 1000 integers. Python program to check whether the given number is a composite number or not.











    Composite numbers